
你好,我試圖確保我的網站只能透過 https 訪問,並且只能透過 www 子網域訪問,我目前使用以下 apache 虛擬主機配置:
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName example.com
ServerAlias www.example.com
# Redirect http requests to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L]
RewriteCond %{HTTP_HOST} !=www.example.com
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=permanent,L]
#..
</VirtualHost>
<VirtualHost *:443>
ServerAdmin [email protected]
ServerName example.com
ServerAlias www.example.com
# Redirect http requests to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L]
RewriteCond %{HTTP_HOST} !=www.example.com
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]
RewriteCond %{SERVER_NAME} !=www.example.com
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,NC,L]
<Directory /home/{apacheuser}/www>
SSLRequireSSL
Order allow,deny
Allow from all
LimitRequestBody 512000
</Directory>
#..
</VirtualHost>
恐怕我對正規表示式的了解相當有限,我想知道這是否是實現這一目標的最佳方法?
謝謝
答案1
只需更換
# Redirect http requests to https RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L] RewriteCond %{HTTP_HOST} !=www.example.com RewriteRule .* https://www.example.com%{REQUEST_URI} [R=permanent,L]
經過
# Redirect http requests to https
RewriteEngine On
RewriteCond %{HTTP_HOST} !=www.example.com
RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L]
就像所有 http 流量都會重定向到 https 除了http://example.com要求
然後從 https 配置中刪除 thoose 行:
# Redirect http requests to https RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L] RewriteCond %{HTTP_HOST} !=www.example.com RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]
所以就保持
RewriteCond %{SERVER_NAME} !=www.example.com
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,NC,L]
答案2
%{SERVER_ADDR}
也可以透過重寫 IP 來實現
編輯:
抱歉,您不能在表達式右側使用變數。
試試這樣的事情:
RewriteCond %{SERVER_NAME},%{SERVER_ADDR} ^(.*),\1
或者如果你不採用動態方式
RewriteCond %{SERVER_NAME} !192.168.1.1