Ad

Redirect Http To Https, Www To Non-www And Remove Last Slash In One Redirect

- 1 answer

is it possible to redirect http to https, www to non-www and remove last slash in one htaccess redirect and it can be seo friendly?

I have this:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

and I don't know how to add to this redirect removing last slash.

Ad

Answer

You may use this code for a single redirect to handle all 3 cases:

RewriteEngine On

## Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteRule ^ %1 [L,E=DELSLASH:1]

# perform redirect for 1. www removal, 2. trailing / removal and 3. http->https
RewriteCond %{ENV:REDIRECT_DELSLASH} =1 [OR]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
Ad
source: stackoverflow.com
Ad