.htaccess conditions: https, www, rewrite



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

  • 将不带 https://* 的用户重定向到 https://*
  • 将具有www.example.com的用户重定向到example.com
  • example.com/index.htm重写为example.com/home
  • 将每个 URI 重定向到索引.htm/home、/background.jpg、/icon.png和/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]

那么,有没有更好的方法来结合httpswww的东西呢?它更像是一种复制和粘贴解决方案,而不是好的代码。我对此知之甚少。

重定向到index.htm正在工作,但我如何防止/background.jpg、/icon.png和/fonts/segoeui.ttf也被重定向?那么将整个事情重写为/home怎么样?


感谢您的帮助!

您只能在一个条件中组合前两个条件

# 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.htms [NC]
RewriteRule ^ /home [R=301,L]
# Rewrite (internally) /home to /index.htm
RewriteRule ^home$ /index.htm [L]

最后,将每个 URI 重定向到索引.htm包括/home、/background.jpg、/icon.png 和/fonts/segoeui.ttf

# 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]

最新更新