尋找一種使用 Apache VirtualHosts 和.htaccess. 我一直在尋找一段時間,并找到了幾種解決方案,但它們都部分作業。
情況如下,在我的.conf檔案中我有一個虛擬主機指定如下:
<VirtualHost *:443>
ServerName example.domain
ServerAlias *.example.domain *.exampledomain.com exampledomain.com
...
</VirtualHost>
<VirtualHost *:80>
ServerName example.domain
ServerAlias *. example.domain *.exampledomain.com exampledomain.com
RewriteEngine on
RewriteCond %{SERVER_NAME} =www.example.domain [OR]
RewriteCond %{SERVER_NAME} =example.domain
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
接下來,我的.htaccess:
RewriteEngine On
Options FollowSymlinks
RewriteBase /
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^www.exampledomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^exampledomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.domain$
RewriteRule ^(.*)$ https://example.domain/$1 [L,R=301]
結果如下:
http://example.domain/ -> https://example.domain/ - (correct)
http://www.example.domain/ -> https://example.domain/ - (correct)
http://exampledomain.com/ -> http://exampledomain.com/ - Forbidden, you dont have access...
http://www.exampledomain.com/ -> http://www.exampledomain.com/ - Forbidden, you dont have access...
https://exampledomain.com/ -> https://example.domain/ - (correct)
https://www.exampledomain.com/ -> https://www.exampledomain.com/ - Connection not secure
我真的不知道哪里出了問題,為什么有些重定向有效而其他重定向無效。任何提示將不勝感激。
uj5u.com熱心網友回復:
如果您有權訪問,<VirtualHost>那么您根本不需要(不應該)使用.htaccess它。
如果目標是僅使用定義的兩個 vHost 在單個重定向中重定向到規范域 ( HTTPS),那么您只需要:
<VirtualHost *:443>
ServerName example.domain
ServerAlias *.example.domain *.exampledomain.com exampledomain.com
RewriteEngine On
# Redirect everything other than the canonical host to the canonical host
RewriteCond %{HTTP_HOST} !=example\.domain
RewriteRule ^ https://example.domain%{REQUEST_URI} [R=301,L]
</VirtualHost>
<VirtualHost *:80>
ServerName example.domain
ServerAlias *.example.domain *.exampledomain.com exampledomain.com
# Unconditionally redirect everything to HTTPS canonical host
Redirect 301 / https://example.domain/
</VirtualHost>
mod_aliasRedirect指令是前綴匹配,匹配后的所有內容都附加到目標 URL 的末尾。因此,Redirect上面的指令將每個 URL 重定向到目標的相同 URL。
您應該首先使用 302(臨時)重定向進行測驗,并且只有在確認它按預期作業后才更改為 301(永久)。您可能需要清除瀏覽器快取,因為瀏覽器會永久快取 301。
看看你的“結果”:
http://exampledomain.com/ -> http://exampledomain.com/ - Forbidden, you dont have access...
http://www.exampledomain.com/ -> http://www.exampledomain.com/ - Forbidden, you dont have access...
vHost:80 容器中當前的 HTTP 到 HTTPS 重定向只是重定向www.example.domain,example.domain并且您可能不接受 vHost:80 容器中的請求,因此任何 HTTP 請求(未重定向到 HTTPS)都可能被阻止。
https://www.exampledomain.com/ -> https://www.exampledomain.com/ - Connection not secure
您的 SSL 證書需要涵蓋所有域和所有別名,否則,您將(充其量)收到瀏覽器 SSL 證書警告,并且瀏覽器將拒絕連接到您的服務器(因此看不到重定向)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/482031.html
