trying to catch all conditions for URL redirect in htaccess file

时间:2018-01-23 19:44:12

标签: php apache .htaccess redirect mod-rewrite

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?

2 个答案:

答案 0 :(得分:1)

这样做:

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]

确保使用新的浏览器进行测试。

答案 1 :(得分:0)

我相信您需要将最后一条规则更改为:

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

虽然文档似乎说RewriteCond %{REQUEST_FILENAME}.php -f可行。测试它证明它没有。如果请求既不是现有文件也不是目录,那么添加斜杠可能不会对您造成伤害。