5 .htaccess重写:强制HTTPS,删除index.php,删除.php,强制www,强制尾随斜杠

我已经阅读了很多文章,似乎无法将所有组合的.htaccess重写一起工作.我要么重新直接循环,要么一个或几个根本不起作用.

为了清楚起见,我正在寻找以下5个,如果需要的话:

>确保所有网址上的www
>确保所有版本站点的HTTPS
>从url中删除index.php
>删除所有.php扩展名/重定向到没有.php扩展名的网址
>可以与前一个一起:添加尾部斜杠

一些例子:

> example.com/index.php => https://www.example.com/
> www.example.com/info/really-good-info.php => https://www.example.com/info/really-good-info/
> www.example.com/about-us.php => https://www.example.com/about-us/
> www.example.com/careers/index.php => https://www.example.com/careers/

这是当前的.htaccess设置:

<IfModule mod_rewrite.c>
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteBase /

# Remove all .php extensions without interfering with .js or .css.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.(?!js|css)([^.]*)$$1\.php

# Remove index from url.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$index?$1 [L,QSA]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index\.php [NC]
RewriteRule ^ %1 [R=301,L]

# Ensure www on all URLs.
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$https://www.example.com/$1 [L,R=301]

# Ensure we are using HTTPS version of the site.
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Ensure all URLs have a trailing slash.
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$https://www.example.com/$1/ [L,R=301]

</IfModule>

上面的.htaccess只在我的根文件夹中,目前需要5个中的3个:更改为HTTPS,添加www并删除index.php.它不会删除任何其他.php文件扩展名,也不会添加尾部斜杠.

最佳答案 我看到2个问题:

重写规则后重定向规则出现
只有在确保存在相应的.php文件后才能添加.php.

这样做:

Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteBase /

# Ensure www on all URLs.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$https://www.%{HTTP_HOST}/$1 [L,R=302]

# Ensure we are using HTTPS version of the site.
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]

RewriteCond %{THE_REQUEST} \s/*(.*?)/index\.php [NC]
RewriteRule ^ %1/ [R=302,L]

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1/ [R=302,L]

# Ensure all URLs have a trailing slash.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^[^.]*?[^/.]$%{REQUEST_URI}/ [L,R=302]

# Remove all .php extensions without interfering with .js or .css.
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+?)/?$$1.php [L]

# Remove index from url.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+?)/?$index.php?$1 [L,QSA]

在测试之前,请务必清除浏览器缓存.

点赞