vespino
vespino

Reputation: 1940

.htaccess redirect addin trailing slash

I have been using the following .htaccess for some time now to redirect non-https to https:

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

This week however an SEO expert told me this gives 2 redirects for links like this:

www.example.com/test

The first to http s ://www.example.com/test The second to http s ://www.example.com/test /

Apparantly this is bad for SEO so I have tried adding a / to the last line, this doesn't work for files, e.g.

www.example.com/test.php => https://www.example.com/test.php/

I have done some searching but I can't seem to find a solution for both issues. Can anyone point me in the right direction?

Upvotes: 0

Views: 38

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

How about adding a check for the directory in the rule (one for directories and one for files):

<IfModule mod_rewrite.c>
RewriteEngine on

# for directories without trailing slashes
RewriteCond %{HTTPS} !=on [NC]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]

# for everything else
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

However, there's a good chance this won't work since the redirect from /test to /test/ isn't happening via Rewrite, but via mod_dir's DirectorySlash directive. If you really want to just make this one redirect (I don't think the impact is that serious), then you can turn DirectorySlash off and have that redirect happen via mod_rewrite instead:

DirectorySlash Off

<IfModule mod_rewrite.c>
RewriteEngine on

# for directories without trailing slashes
RewriteCond %{HTTPS} !=on [NC]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]

# for everything else
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Add trailing slashes for directories that have them missing
RewriteCond %{HTTPS} on [NC]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

Upvotes: 2

Related Questions