Code Monkey home page Code Monkey logo

server-configs-apache's Introduction

Server CI

Apache Server Configs is a collection of configuration snippets that can help your server improve the website's performance and security, while also ensuring that resources are served with the correct content-type and are accessible, if needed, even cross-domain.

Getting Started

There are two options for getting the Apache server configs:

  • If you have access to the main server configuration file (usually called httpd.conf), you should configure Apache this way. This is usually the recommended way, as using .htaccess files slows down Apache!
  • If you don't have access to it, which is quite common with hosting services, checkout the .htaccess guide.

Using the Apache server configs repo directly has a few required steps to be able to work.

See also the Apache Getting Started.

Check httpd.conf settings

The first thing to check is that the httpd.conf file contains appropriate values for your specific install.

Most specific variables are:

  • ServerRoot
  • User
  • Group
  • ErrorLog
  • CustomLog
  • TypesConfig (ensure that the path for the mime.types file is valid)

Apache test and restart

  • To verify Apache config

    apache2 -t
  • To verify Apache config with a custom file

    apache2 -t -f httpd.conf
  • To reload Apache and apply the new config

    apache2ctl reload

Enable Apache httpd modules

Some configurations won't have any effect if the appropriate modules aren't enabled. So, in order for everything to work as intended, you need to ensure you have the following Apache modules enabled:

For more detailed information on configuration files and how to use them, please check the appropriate Apache documentation:

Standalone

These instructions should work on any distribution where apt-get has been used to install Apache.

  1. Open up a terminal and type the following command. Enter your password when prompted.

    sudo a2enmod setenvif headers deflate filter expires rewrite include
  2. Restart apache by using the following command, so the new configuration takes effect.

    sudo /etc/init.d/apache2 restart

With MAMP/WAMP/XAMPP

  • MAMP PRO. On the main screen, click the Apache tab and ensure that all the required modules are 'checked', indicating they are enabled.

  • WampServer. If you have installed WampServer just click on the icon in the task bar then Apache section then modules section. You will be presented with a list of modules. Simply click on a module name to enable it. WampServer will automatically restart the Apache service after you enable a module.

  • Others. Locate the httpd.conf file, which is typically found in:

    • MAMP: /Applications/MAMP/conf/apache/httpd.conf
    • XAMPP: /Applications/XAMPP/etc/httpd.conf
    • WAMP: C:\apache\conf\httpd.conf

    Open the file in a text editor and uncomment all the required modules. Once you have done so, reset MAMP/WAMP/XAMPP.

Basic structure

This repository has the following structure:

./
├── vhosts/
│   ├── 000-default.conf
│   └── templates/
├── h5bp/
│   ├── basic.conf
│   └── .../
└── httpd.conf
  • vhosts/

    This directory should contain all the server definitions.

    Except if they are dot prefixed or non .conf extension, all files in this folder are loaded automatically.

    • templates folder

      Files in this folder contain a <VirtualHost/> template for secure and non-secure hosts. They are intended to be copied in the vhosts folder with all example.com occurrences changed to the target host.

  • h5bp/

    This directory contains config snippets (mixins) to be included as desired.

    There are two types of config files provided, individual config snippets and combined config files which provide convenient defaults.

    • basic.conf

      This file loads a small subset of the rules provided by this repository to add expires headers, allow cross-domain fonts and protect system files from web access. The basic.conf file includes the rules which are recommended to always be defined.

  • httpd.conf

    The main Apache config file.

Usage

The default location of the configuration files is /usr/local/apache2/, but these files may be located any of a variety of places, depending on how exactly you installed the server.
Common locations for these files may be found in the httpd wiki.

As a reference

To use as reference requires no special installation steps, download/checkout the repository to a convenient location and adapt your existing httpd configuration incorporating the desired functionality from this repository.

Download the latest release archive.

Directly

To use directly, add httpd config files from this repository.
For example:

apache2ctl stop
git clone https://github.com/h5bp/server-configs-apache.git /tmp/h5bp-apache
cd /usr/local
cp -r apache2 apache2-previous
cp -r /tmp/h5bp-apache/* apache2
# install-specific edits
apache2ctl start

Manage sites

cd /usr/local/apache2/vhosts
  • Creating a new site

    cp templates/example.com.conf .actual-hostname.conf
    sed -i 's/example.com/actual-hostname/g' .actual-hostname.conf
  • Enabling a site

    mv .actual-hostname.conf actual-hostname.conf
  • Disabling a site

    mv actual-hostname.conf .actual-hostname.conf
apache2ctl reload

.htaccess file

Usage

Just copy the .htaccess file in the root of the website.

Getting options:

  • Download the h5bp.htaccess on the latest release and rename the file to .htaccess
  • Install them via npm: npm install --save-dev apache-server-configs Inside the dist/ folder, you'll find a ready-to-use .htaccess file.

Custom .htaccess builds

Security, mime-type, and caching best practices evolve, and so should do your .htaccess file. In the past, with each new Apache Server Configs release it was quite tedious to find out which .htaccess trick was just new or only had changes in certain nuances.

The build script with its re-usable and customizable build configuration lets you easily update your .htaccess file. Each new .htaccess build will contain the updated Apache Server Configs source files, enabled or commented-out according to your settings in the htaccess.conf of your project root.

Configuration file: htaccess.conf

It allows you to define which module to enable or disable for your project. Just copy the default htaccess.conf from this repo into your project directory. Adjust to your needs, and/or add custom code snippets you need for your project. Its syntax is straight and pretty much self-explanatory:

# Example Module

title   "example module"
enable  "src/example-module/images.conf"
enable  "src/example-module/web_fonts.conf"
disable "src/example-module/not-needed.conf"
omit    "src/example-module/not-needed-at-all.conf"

#... more modules ...
Disabling modules

For example, the “Cross-origin web fonts” snippet is always included in our pre-built .htaccess file and enabled. If your project does not deal with web fonts, you can disable or omit this section:

This will comment out the section:

disable  "h5bp/cross-origin/web_fonts.conf"

…and this will exclude the section, saving lines in output:

omit  "h5bp/cross-origin/web_fonts.conf"
Enabling modules

For example, the “Forcing https:// snippet is disabled by default, although being included in our pre-built .htaccess. To enable this snippet, change the disable keyword to enable:

enable "h5bp/rewrites/rewrite_http_to_https.conf"
Controlling the size of the output .htaccess file

The default partials contain significant numbers of comment lines, which contain valuable guidance about how and why to use the setting as well as web references. However, some may feel that the size of the resulting .htaccess file is too large.

The special keyword no-partials-comments can be used to prevent comment lines from being copied out of the partials into .htaccess.

Note

This keyword does not control comments created by the build script (such as title or disabled directives), only those that are in the source partials files.

no-partials-comments
Adding custom modules

Imagine you're passing all requests to non-existing files to your favorite web framework. The according mod_dir snippet would go like this:

FallbackResource index.php

Store this snippet in a file, e.g. config/framework_rewrites.conf, and add a reference in your htaccess.conf:

# PROJECT MODULES
enable "config/framework_rewrites.conf"

Build script: build.sh

Dive into your project root and call the build script from wherever you cloned the repo. Here are three examples:

  1. Create a default .htaccess

Create a default .htaccess in the current work directory. An existing htaccess.conf in this directory will be used; if none is present, the default configuration will apply.

$ path/to/server-configs-apache/bin/build.sh

# Output looks like:
[✔] Build .htaccess
[✔] Moved in place: './.htaccess'
  1. Custom output location

Just add an output path and filename as a parameter. By the way, if there's an existing .htaccess file, the build script will create a backup.

$ path/to/server-configs-apache/bin/build.sh htdocs/.htaccess
[✔] Build .htaccess
[✔] Create backup: 'htdocs/.htaccess~'
[✔] Moved in place: 'htdocs/.htaccess'
  1. Custom .htaccess configuration

Why not maintain your personal ~/htaccess.conf? This example creates a .htaccess in the current work directory, according to your favorite settings you may have stored in your $HOME directory:

path/to/server-configs-apache/bin/build.sh ./.htaccess ~/htaccess.conf

Support

  • Apache v2.4.17+

Contributing

Anyone is welcome to contribute, however, if you decide to get involved, please take a moment to review the guidelines:

Acknowledgements

Apache Server Configs is only possible thanks to all the awesome contributors!

License

The code is available under the MIT license.

server-configs-apache's People

Contributors

ad7six avatar adeelejaz avatar alrra avatar bchr avatar chuanxshi avatar clarkni5 avatar creopard avatar dependabot[bot] avatar drublic avatar h5bp-bot avatar hatzopoulos avatar jamieburchell avatar jingman avatar laukstein avatar leocolomb avatar malvoz avatar mathiasbynens avatar mattbrundage avatar midzer avatar mikealmond avatar mikewest avatar necolas avatar ngryman avatar nlemoine avatar paulirish avatar phize avatar tomkyle avatar westhouseit avatar wraithkenny avatar xhmikosr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

server-configs-apache's Issues

Conflict between deflate and include

Hi,

I'm trying to setup my website with both

AddOutputFilterByType DEFLATE "text/css"

and

<FilesMatch "\.combined\.css$">
Options +Includes
AddOutputFilterByType INCLUDES text/css
SetOutputFilter INCLUDES
</FilesMatch>

My css is called site.combined.css and it works only if i have a single line in the file. So this works
<!--#include file="css/layout/reset.css" -->

As soon as i put another line in it, it wont work anymore. So this doesn't work.
<!--#include file="css/layout/reset.css" -->
<!--#include file="css/cake.css" -->

I've narrowed it down to the deflate. If i remove the deflate from text/css then it will include and concatenate both files correctly.

I'm on Windows with Apache 2.4.9
Thanks!

Setting Cache-Control

Hello guys I'm new here but, I gues we are following best practices here or maybe settings cache-control is not a best practice as I think? Sorry if this issue is a false one. In the .htaccess there is no Cache-Control public or private I guess it should be there what you think?

"AddType text/html php" within mod_mime results in blank pages

First, thank you for maintaining this project. It's been greatly helpful.

Using CentOS 6, Apache 2.4.12, PHP 5.4.38, the following .htaccess line brings down a PHP-powered site -- results in blank pages:

AddType   text/html   php

Of what I've read about the above, it appears to be proper, but still wanted to report what occurred when I implemented it on my live, vanilla setup.

Thanks.

FCGI Authorization header

Not a problem with this config but if you run php under FCGI, the Authorization header will be stripped. An easy fix would be to add "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]".

Allow `ETags` for HTML files

Current situation in .htaccess:

<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None
ExpiresByType text/html "access plus 0 seconds"

This forces the client to reload HTML files regardless of whether or not they have changed.

I propose this:

<FilesMatch "(?<!\.html)$">
    <ifModule mod_headers.c>
        Header unset ETag
    </IfModule>
    FileETag None
</FilesMatch>

This will make apache generate ETags for HTML files.

Now, in the rare(?) case of server clustering, the client may still be forced to reload as mentioned in https://developer.yahoo.com/performance/rules.html#etags. Without server clustering the client benefits from ETags, and receives a 304 response.

Bottom line: most users will take advantage of this configuration, and the situation is unchanged for the rest.

Syntax Highlight .conf files as ApacheConf for GitHub and/or Vim

I thought it would be nice for this repo to enable ApacheConf syntax highlighting on all the *.conf files in the repository.

As far as I know, there are two ways to accomplish this:

(1) Rename all the .conf files to .apacheconf to be in line with github/linguist and then refactor the build scripts with the new extensions. Although this change could likely upset a few people's forks. Here's a branch of this change (subsequently going this way wouldn't need the .gitattributes PR I made earlier)

or (2) prepend to all .conf files something like below, although perhaps vim: syntax=apache is not really needed. Going this route though, we would have to strip out the vim modelines in the build process.

# vim: set filetype=apache:
# vim: syntax=apache

Let me know if interested. Related to #74

SVG as image mimetype

I just uploaded a site using the stock htaccess, and the site uses a logo img with an svg source
<img src="img/logo.svg">

Chrome was giving me the old:
Resource interpreted as Image but transferred with MIME type text/xml

Simple fix was adding
AddType image/svg+xml svg
in my case on line 171

AddType text/cache-manifest appcache manifest

Now that people will be using SVG more often and in different ways: img, svg, object, background image, it might be good to include this as a default. I'm not sure if any others MIME types are needed for other use cases.

No gzip compression with Apache 2.2.22-14

Dreamhost run Apache 2.2.22-14 on my box (and probably others), and when I use this .htaccess my assets aren't gzipped.

Reverting to an older H5BP configuration (which is what I currently use, see below), results in gzipped assets.

<IfModule mod_deflate.c>

  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
  <IfModule filter_module>
    FilterDeclare   COMPRESS
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/x-icon
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
    FilterChain     COMPRESS
    FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
  </IfModule>

  <IfModule !mod_filter.c>
    # Legacy versions of Apache
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
  </IfModule>

</IfModule>

Add SSL section

It would be fantastic to have an optimised/secured SSL section:

  • disable insecure cyphers
  • disable insecure protos
  • enable/disable renegotiation

and so on ..

Remove only-http from www-normalizing redirects

Most users probably aren't using both http and https, but if they are it's possibly confusing/misleading why these redirects only apply to http requests.

So, as mentioned in #49 the RewriteCond %{HTTPS} =on conditions should be removed before the next major release.

optimize apache example.com => www.example.com

use

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{SERVER_ADDR} !=127.0.0.1

replace

RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
RewriteCond %{HTTP_HOST} !=localhost [NC]
RewriteCond %{HTTP_HOST} !=127.0.0.1

because:

  1. save bits;
  2. cover some non localhost virtual host such as a DIY xx.dev instead of localhost using hosts.

anyone agree?

Consider sending `.jsonld` files with the `application/ld+json` content-type

Consider adding AddType application/ld+json jsonld, as JSON-LD (JSON for Linking Data) is in the final stages of standardization at W3C, and it seems the adoption is quite good.

Useful links:

My question(s): Does sending .jsonld files with a different Content-Type then application/ld+json (e.g.: application/json) have any downsides ? Or to put it differently: do we really need this new Content-Type ?

(Cc: @gkellogg, @lanthaler, @msporny)

Add configs for TopoJSON files

Specification: https://github.com/topojson/topojson-specification

File extension: .topojson
Media type: Couldn't find any information about the recommended media type. Maybe simply go with application/json (or with the same media type as GeoJSON, namely, application/vnd.geo+json)?

Cc: @calvinmetcalf, @mbostock

Things that need to be done:

  • set media type
  • set expires headers
  • ensure that TopoJSON files:
    • are served with the charset parameter that specifies that the character encoding of the documents is utf-8
    • are compressed (it's JSON, so it will compress quite nicely)
    • aren't served with all the HTTP headers intended only for HTML documents
  • other (which?).

Double quotes around file types lead to Error 500

Since the latest version you added double quotes around the file types on AddCharset (https://github.com/h5bp/server-configs-apache/blob/master/src/.htaccess#L226). On a newly installed XAMPP (Windows, latest version) this leads to Error 500 - with the following message in the error.log:

Invalid command '.vtt', perhaps misspelled or defined by a module not included in the server configuration

After I removed the " around the file types, everything is working again.

Add `ServerSignature`?

This is what the default /etc/apache2/conf.d/security file says:

#
# Optionally add a line containing the server version and virtual host
# name to server-generated pages (internal error documents, FTP directory
# listings, mod_status and mod_info output etc., but not CGI generated
# documents or custom error documents).
# Set to "EMail" to also include a mailto: link to the ServerAdmin.
# Set to one of:  On | Off | EMail
#
#ServerSignature Off
ServerSignature On

https://httpd.apache.org/docs/current/mod/core.html#serversignature

It wouldn’t hurt to explicitly add ServerSignature Off to the config (although it is the default value).

Filename-based cache busting issue for Apache 2.2+

In the Apache RewriteRule that manages filename-based cache busting, the RewriteCond directive no longer work as intended for Apache versions 2.2+

Luckily the fix is quite simple; all you need to do is add the DOCUMENT_ROOT variable before the REQUEST_FILENAME variable.

Apache < 2.2:

RewriteCond %{REQUEST_FILENAME} !-f

Apache > 2.2:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f

On Apache 2.2.29 I've confirmed that the cache-busting RewriteRule works as intended after making this change (i.e. Apache serves the resource whose filename happens to match the regexp pattern).

Serve WOFF 1.0 font files compressed?

According to the people from Zoompf (see blog post), it might be worth serving WOFF 1.0 font files compressed (even thought they are compressed by default):

Yes, WOFF files are natively compressed. However, their compression is not very good. I have WOFF files reduced 30-50% using HTTP compression. Clearly the native compression falls short. In fact, one of the primary reasons WOFF File Format 2 was even created was “to provide improved compression and thus lower use of network bandwidth, while still allowing fast decompression even on mobile devices. This is achieved by combining a content-aware preprocessing step and improved entropy coding, compared to the Flate compression used in WOFF 1.0"

See also: http://www.w3.org/TR/WOFF/


Being curious about this, I wanted to see some more data, so I generate some (the results are posted in the following comments).

How the data was generated

  1. Downloaded the fonts (+ variations of the fonts) from Google Fonts in TrueType format - .ttf (didn't wanted to use the WOFF version, as Google recently switched to using Zopfli, which makes the size of the .woff files smaller then normal).
  2. Converted the .tff files to .woff (+ got the size of the .woff file - Size (Original))
  3. Added the .woff files on Apache/2.4.7 (Ubuntu), enabled compression (+ made requests to get the size of the compressed .woff files - Size (Compressed))

My results

Graphs

Expanding the 0-10% from the above graph, it looks like this:

My verdict

  • It general it doesn't seem to be worth it.

Thoughts?

Add configs for WOFF 2.0 font files

Specification: http://www.w3.org/TR/WOFF2/
Browser Support: Chrome 36+

Other links:

- Extension: `.woff2` (commonly used/suggested) - Media type: `font/woff2` (commonly used/suggested)

EDIT: see #32 (comment).

Note: from my tests the file extension and the media type don't matter (at least, not in Chrome)

unused mobile directories/subdomains and common mistyping

I gather that, because some websites deal with mobile design by creating separate directories for content formatted to fit (while others use responsive CSS), some users or user agents might attempt to visit such directories. For responsive design, I've seen advice to redirect visits to certain subdomains and directories to the home page. For directories, since redirection is handled in the .htaccess file (my host runs Apache), I've added something like the following to mine:

RedirectPermanent /i http://example.com
RedirectPermanent /mobile http://example.com
RedirectPermanent /mobi http://example.com

I added /mobi because, if the TLD *.mobi grows in use, people may search for that as a directory, even though erroneous, so we may as well catch it in <.htaccess>.

Perhaps this should be added to H5BP's model .htaccess file, as an option for either commenting out or decommenting.

The third-level domains m and wap (as in m.example.com and wap.example.com) could be handled for the same reason by setting them up as aliases and perhaps that should be suggested somewhere in H5BP's documentation.

I forgot where I saw the advice, so I don't know whom to credit.

Firefox responds to failed attempts to reach Web addresses by suggesting proofreading one's typing, giving "ww.example.com" as the illustration. So I added that as an alias at my host. If Firefox is right to to give that error primacy, maybe it's common, and it should be added to H5BP's documentation as a suggestion.

This was originally suggested at h5bp/html5-boilerplate#1710 and moving here was invited.

Add `TraceEnable`

This is what the default /etc/apache2/conf.d/security file says:

#
# Allow TRACE method
#
# Set to "extended" to also reflect the request body (only for testing and
# diagnostic purposes).
#
# Set to one of:  On | Off | extended
#
TraceEnable Off
#TraceEnable On

https://httpd.apache.org/docs/2.2/mod/core.html#traceenable

It wouldn’t hurt to add TraceEnable off to the config (overriding the default value on).

Integrate the `mobile-boilerplate` Apache configs

Integrate whatever is useful from the Apache configs from the mobile-boilerplate repository:

.htaccess: enabling "forcing https" and "suppressing the www." does not remove subdomain

In the .htaccess If I enable:

  • The forcing of https
  • redirection for www. prefixed urls to urls without the prefix

The visitor is not redirected from www.example.com to https://example.com, as I would have expected. Instead, the user is redirected to https://www.example.com (so the prefix isn't removed).

I am not an expert in htaccess url rewriting, but it seems like the subdomain is only removed for http connections and it redirects to the unprefixed, but unsecured version of the url (so it doesn't do anything for https connections). Wouldn't it be better to rewrite secure connections as well? Just wondering if this is an oversight or by design.


# ----------------------------------------------------------------------
# | Forcing `https://`                                                 |
# ----------------------------------------------------------------------

# Redirect from the `http://` to the `https://` version of the URL.
# https://wiki.apache.org/httpd/RewriteHTTPToHTTPS

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{HTTPS} !=on
   RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
</IfModule>

# ----------------------------------------------------------------------
# | Suppressing / Forcing the `www.` at the beginning of URLs          |
# ----------------------------------------------------------------------

# The same content should never be available under two different
# URLs, especially not with and without `www.` at the beginning.
# This can cause SEO problems (duplicate content), and therefore,
# you should choose one of the alternatives and redirect the other
# one.
#
# By default `Option 1` (no `www.`) is activated.
# http://no-www.org/faq.php?q=class_b
#
# If you would prefer to use `Option 2`, just comment out all the
# lines from `Option 1` and uncomment the ones from `Option 2`.
#
# (!) NEVER USE BOTH RULES AT THE SAME TIME!

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Option 1: rewrite www.example.com &#8594; example.com

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

Full .htaccess that led to this behaviour here

Allow access to the content from within the `/.well-known/` directory.

From https://www.mnot.net/blog/2010/04/07/well-known:

One of the nagging theoretical problems in the Web architecture has been finding so-called “site-wide metadata”; i.e., finding something out about a Web site before you access it. We wrestled with this in P3P way back when, and the TAG took it up after that.

The easy solution to this is to define a static “well-known” URL — like /robots.txt. However, having a third party come along and squat on part of every Web site’s URL namespace is less than friendly, and eventually it’ll lead to conflicts.

So, in a less-than-ideal but practical solution, RFC5785 now defines a sandbox for these well-known URIs — /.well-known/, and provides a registry for them to assure that they won’t conflict.

See also: http://tools.ietf.org/html/rfc5785

Javescript compression in .htaccess

I've used the 'compression' section of the .htacess file & noticed (thanks to gzipwtf.com) that the Javascript compression doesn't seem to work. It would seem there is a missing reference to text/javascript.

Here is the updated code snippet that I used, hope it helps:

<IfModule mod_deflate.c>

    # Force compression for mangled headers.
    # http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ 

HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Compress all output labeled with one of the following MIME-types
    # (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
    #  and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
    #  as `AddOutputFilterByType` is still in the core directives).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/javascript \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>

[This has been migrated from https://github.com/h5bp/html5-boilerplate/issues/1592]

Should this repo be .conf files?

This topic has come up in the past numerous times, some references:

The use of an optimized.htaccess file is a great improvement compared to a standard apache install - but it is really just a stepping-stone solution to configuring apache appropriately.

It's kind of hard to cater for all uses but e.g. potential users of this repo include:

  • frontend developers using html5-boilerplate
  • users, wanting to optimize their site
  • developers using html5-boilerplate as part of their project
  • server-savvy users

Right now, the first two groups are catered for pretty well - you can drop in the .htaccess file into any project and it just works, and is an improvement. Perhaps they can't modify their apache config files, so it's the only solution that works for them - though arguably shared hosting is less common than in the past, being replaced by vps servers, reducing the significance/relevance of this point.

The last two groups however are not catered for particularly well, a (general) developer using apache may be aware that they could avoid using .htaccess files but, through convenience of using the files provided probably won't. A user familiar with apache either won't use the repo at all (and these are the users who could provide the most benefit in terms of future contributions), or needs to spend some time integrating the provided rules into their existing config files.

Perhaps only the boilerplate repo should have/include the .htaccess file (generated by some build script).

One way or another, I feel that users should be guided to the best way to use apache, not stopping just short of the finish line.

Comments?

Add configs for web application manifest files

Specification: http://w3c.github.io/manifest/
Browser support coming soon in: Chrome and Firefox


The web application manifest file:

    1. Must be served with the correct Content-Type, namely: application/manifest+json.

    From http://w3c.github.io/manifest/#h3_obtaining-a-manifest:

    It seems we cannot reliably set the Content-Type from the .htaccess file, because:

    • if <link rel="manifest"...> is used, we can't know the exact location and name of the manifest file

    • if <link rel="manifest"...> is NOT used, the location of the manifest is assume to be /.well-known/manifest.json, but even this default location can't be (AFAIK) correctly matched from within the .htaccess file, as it requires the use of a directive such as <Location>, e.g.:

      <Location "/.well-known/manifest.json">
        AddType application/manifest+json json
      </Location>

      Also, doing something like:

      <Files "manifest.json">
        AddType application/manifest+jsonx json
      </Files>

      isn't a good default, as it will match all files with that specific name.

      So, we will just have to add a comment (with some examples), and let the user handle this part.

    1. Can be served compressed (it's JSON, so it will compress quite nicely):
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      # ...
                                      application/manifest+json \
                                      # ...
    </IfModule>
    1. Can be cached

    <IfModule mod_expires.c>
        # ...
        ExpiresByType application/manifest+json             "access plus 1 year"
        # ....
    </IfModule>
    1. Can be UTF-8 encoded (already solved because the manifest file needs to have the file extension json or manifest):
    <IfModule mod_mime.c>
        AddCharset utf-8 .atom .css .js .json .jsonld .rss .vtt .webapp .xml
    </IfModule>
    1. Should NOT be served with all the HTTP headers intended only for HTML documents (already solved because the manifest file needs to have the file extension json or manifest):
    <IfModule mod_headers.c>
        # ...
        <FilesMatch "\.(appcache|atom|crx|css|cur|eot|f4[abpv]|flv|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|tt[cf]|txt|vcf|vtt|webapp|web[mp]|woff|xml|xpi)$">
            Header unset Content-Security-Policy
            Header unset X-Frame-Options
            Header unset X-UA-Compatible
            Header unset X-XSS-Protection
        </FilesMatch>
    </IfModule>
    1. Other (Which?)

www "removal" not working

I've incorporated the Apache Server Configs by adding this line to my /etc/apache2/apache2.conf file:

Include apache-server-configs.conf

And putting that file into /etc/apache2. A restart of the server and I get no warnings/errors so I assume it's in place.

Yet when I visit any of my sites using www.domain.com, it doesn't redirect to domain.com. Is there something else I have to do? That section of the conf file is uncommented.

<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

And mod_rewrite is definitely enabled.

Rewrite rules not working in Apache config file

In reference to issue #876: I created an apache config file under /etc/apache2/html5boilerplate.conf and included it into /etc/apache2/apache2.conf:

...

# Include generic snippets of statements
Include conf.d/

# HTML5 BOILERPLATE MAGIC
Include html5boilerplate.conf

# Include the virtual host configurations:
Include sites-enabled/

Everything seems to work just fine (like expire header, E-Tag, ...) but the RewriteRules do not work. I used the "Filename-based cache busting" in one of my projects and after moving everything from the .htaccess to the config file, this rewrite was broken. In fact, all rewrites where broken, as I didn't turned the RewriteEngine On again in the .htaccess file.

Is there any setting in my apache2.conf that needs to be set to be able to use RewriteRule in a config file?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.