.htaccess条件:https,www,重写

时间:2017-05-23 10:25:51

标签: php apache .htaccess redirect mod-rewrite

想在我的网站上使用.htaccess重写mod执行以下操作:

  • 将没有https:// *的用户重定向到https:// *
  • www.example.com 的用户重定向到 example.com
  • example.com/index.htm 重写为 example.com/home
  • 将每个URI重定向到 / home /background.jpg /icon.png index.htm 。 em>和 /fonts/segoeui.ttf

这是我已有的代码:

RewriteEngine On
RewriteBase /

RewriteRule ^\.htaccess$ - [F]

# --- Part that looks stupid but is working ---
RewriteCond %{SERVER_PORT} !^443 
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www\.([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# --- Part that is not really working ---
RewriteCond %{REQUEST_URI} !^/(index\.htm)?$ [NC]
RewriteRule ^.*$ /index.htm [L,R=301]

那么,有没有更好的方法来结合 https www 这个东西?它比复杂的代码更像是一个复制和粘贴解决方案。我对此并不了解。

重定向到 index.htm 正在运行,但是如何阻止 /background.jpg /icon.png /fonts/segoeui.ttf 也被重定向了?然后将整个事情重写为 / home

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

您只能在一个

中组合前两个条件
# Force https and non-www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

然后,重写example.com/index.htm到example.com/home

# Redirect /index.htm to /home and avoids infinite redirect loop
RewriteCond %{THE_REQUEST} \s/index\.htm\s [NC]
RewriteRule ^ /home [R=301,L]

# Rewrite (internally) /home to /index.htm
RewriteRule ^home$ /index.htm [L]

最后,将每个URI重定向到/ home,/ background.jpg,/ icon.png和/fonts/segoeui.ttf

的index.htm exept
# Redirect (if not an existing file) to /index.htm (which will after redirect to /home)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.htm [R=301,L]