我非常感谢您对以下内容的帮助。我一直在谷歌搜索和测试代码通过试验错误,我相信我正在慢慢搞清楚,但我会感谢结果和我的学习发展的快速跟踪。
我目前通过GoDaddy在apache Linux服务器上的共享资源上托管了一个网站。我正在努力实现以下目标; -
1)将非www流量重定向到www。
2)删除.html文件扩展名并在网址上添加一个尾部斜杠。
我目前有以下代码,301 www。重定向正在工作,尾随斜杠也在工作。但是我在子页面上遇到404错误,即www.swiftcomm.co.uk/contact /; -
如何使用代码解决此问题?
Options +FollowSymlinks -MultiViews -Indexes
RewriteEngine on
# Redirect to domain with www.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Same for HTTPS:
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Ensure all directory URLs have a trailing slash.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\/$
RewriteCond %{REQUEST_URI} !\/[^\/]*\.[^\/]+$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}/ [L,R=301]
# Same for HTTPS:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\/$
RewriteCond %{REQUEST_URI} !\/[^\/]*\.[^\/]+$
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI}/ [L,R=301]
答案 0 :(得分:0)
请尝试以下代码 - 它可以替换整个文件。这些评论解释了每个规则集的作用。
Options +FollowSymlinks -MultiViews -Indexes
RewriteEngine on
RewriteBase /
# Force www. prefix - http/https
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=302,L]
# Remove .html extension suffix from URI only if it matches an existing file.
# Add trailing slash simultaneously.
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{THE_REQUEST} \s\/(.+)\.html\s [NC]
RewriteRule ^ %1/ [R=302,L]
# Force trailing slash if it has'nt been forced already.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^\/(.+[^/])$
RewriteRule ^ %{REQUEST_URI}/ [R=302,L]
# Rewrite non-existing files to their .html counterparts.
# If the .html file does not exist, Apache will gracefully degrade to a 404.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ $1.html [L]