R2D2
R2D2

Reputation: 2640

trying to catch all conditions for URL redirect in htaccess file

I am trying to create a htaccess file that will redirect all possible URLs to the correct format.

I want all URLs to be in the format:

https://www.mywebsite.co.uk/mypage

All my website pages are filename.php

My current htaccess code is as follows:

RewriteEngine On

RewriteBase /

# Force WWW prefix
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Force SSL
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# Remove .php extension
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/(.+)/$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^(.*)/$ $1.php [L]

# Force trailing slash
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .*[^/]$ $0/ [L,R=301]

This works well for almost all conditions, but if I click on a link like this:

https://www.mywebsite.co.uk/mypage

This should automatically redirect to:

https://www.mywebsite.co.uk/mypage/

But it doesn't redirect, and doesn't add the trailing slash.

How can I add to my current htaccess file to catch this condition as well?

Upvotes: 1

Views: 161

Answers (2)

anubhava
anubhava

Reputation: 785531

Have it this way:

Options -MultiViews
RewriteEngine On
RewriteBase /

# Force WWW prefix
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# Force SSL
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# Remove .php extension
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]

# Force trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/$ $1.php [L]

Make sure to use a new browser for your testing.

Upvotes: 2

Jonas Äppelgran
Jonas Äppelgran

Reputation: 2747

I believe that you need to change your last rule to this:

# Force trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .*[^/]$ $0/ [L,R=301]

While the documentation seems to say that RewriteCond %{REQUEST_FILENAME}.php -f could work. Testing it proves it doesn't. And if the request is neither a existing file or directory it probably won't hurt you to add that slash.

Upvotes: 0

Related Questions