4

I would like to accomplish the following:

  • rewrite non-www to www
  • redirect from http to https
  • remove trailing slash

e.g. http://example.co.uk should redirect to https://www.example.co.uk

How would you structure a set of rules to do all of the above?

3

2 Answers 2

9

For your first two rewrites (non-www → www, http → https), the following rule should work:

RewriteEngine On

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !=www.example.com [NC]
RewriteRule ^(.*) https://www.example.com/$1 [NS,L,R=permanent]

Just replace www.example.com with the actual canonical hostname of your site.

As for your third point, there's no need to add or remove trailing slashes from URLs with an empty path, since such URLs are treated as canonically equivalent by all standards-conforming HTTP clients (including browsers and search engines).

Ps. If you want your site to be always accessed over HTTPS, you'll probably also want to configure your web server to send the HTTP Strict Transport Security header. For example, in Apache you could do that with the following directive (mostly copied from the linked Wikipedia article):

<If "-T %{HTTPS} && %{HTTP_HOST} = 'www.example.com'">
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</If>
0

NON-WWW URLS TO WWW WITH HTTPS USING HTACCESS:

You can add the following code to your .htaccess file, you can find it in your website root directory, if you don't find it you can copy this in a text editor and save it as .htaccess, then upload it.

p.s.: Make sure that you backup the .HTACCESS file before you proceed. Incorrect codes can lead to 500 errors.


RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Remove trailing slash

Be careful when turning off the trailing slash. If your host has mod_dir enabled, make sure that you turn off the directory slash, which is enabled by default. This directive will add a trailing slash at the end of a directory regardless of the rules you set up. To disable this, add this to the top of your htaccess file:

DirectorySlash Off

Your browser and even your server, by default, add a trailing slash to a directory. It is done for a reason. If you must strip the trailing slash though, this is how you would do it:


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.