使用 .htaccess 用一个 PHP 文件处理所有请求:
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^?]*)$ /index.php [NC,L,QSA]
用于固定链接的 WordPress .htaccess 文件
(这是本节中唯一包含 RewriteEngine on 规则的规则。)
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
使用 .htaccess 以通用方式强制 WWW:
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
使用 .htaccess 强制非 www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
使用 .htaccess 以通用方式强制非 www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
使用 .htaccess 强制 HTTPS:
使用此方法将非 HTTPS 请求重定向到 HTTPS 请求。例如,如果你访问 https://example.com/,它将重定向到 https://example.com。
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
在代理后使用 .htaccess 强制 HTTPS:
如果您的服务器前有代理执行 TLS 终止,这会很有用。
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
使用 .htaccess 强制添加结尾斜杠
使用以下 .htaccess 规则,将任何没有以斜杠结尾的请求重定向到相同的 URL(但带有结尾斜杠)。例如,将 https://example.com/your-page 重定向到 https://example.com/your-page/
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
使用 .htaccess 删除尾部斜杠
使用此方法可以删除任何尾部斜杠(它会 301 重定向到没有尾部斜杠的 URL)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
使用 .htaccess 重定向单个页面
将单个 URL 重定向到新位置
Redirect 301 /oldpage.html https://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html https://www.yoursite.com/folder/
使用 .htaccess 为单个目录设置别名
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1
使用 .htaccess 的脚本别名路径
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
其他 .htaccess 规则:https://hostscore.net/learn/htaccess-guide/