Mobile app version of vmapp.org
Login or Join
Voss4911412

: Apache Rewrite Rule non-www to www + http to https + remove trailing slash I would like to accomplish the following: rewrite non-www to www redirect from http to https remove trailing slash

@Voss4911412

Posted in: #Apache #Https #ModRewrite #NoWww #Redirects

I would like to accomplish the following:


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


e.g. example.co.uk should redirect to www.example.co.uk
How would you structure a set of rules to do all of the above?

10.02% popularity Vote Up Vote Down


Login to follow query

More posts by @Voss4911412

2 Comments

Sorted by latest first Latest Oldest Best

 

@Cody1181609

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 ^(.*)$ www.%{HTTP_HOST}/ [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 ^(.*)$ www.domain.com/ [R=301,L]

10% popularity Vote Up Vote Down


 

@Rambettina238

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 ^(.*) www.example.com/ [NS,L,R=permanent]


Just replace 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>

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme