Apache-2.2

mod_rewrite:將 https://example.com 重定向到 https://sub.example.com

  • March 23, 2014

我有一個在 Apache 伺服器上執行的域 example.com,我想將每個對 https://example.com 的呼叫重定向https://sub.example.com

我有一個這樣配置的虛擬主機:

<VirtualHost _default_:80>
       ServerName sub.example.com
       RewriteEngine On
       RewriteCond %{SERVER_PORT} !^443$
       RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
</VirtualHost>

<IfModule mod_ssl.c>
<VirtualHost _default_:443>
       RewriteEngine On
       RewriteCond %{HTTP_HOST} ^https://%{HTTP_HOST}/$1
       RewriteRule ^(.*)$ https://cloud.%{HTTP_HOST}/$1 [R=301,L]

       ServerName sub.example.com
       ServerAdmin gnarf
       DocumentRoot /var/www/subfolder
       <Directory />
               Options FollowSymLinks
               AllowOverride None
       </Directory>
       <Directory /var/www/>
               Options Indexes FollowSymLinks MultiViews
               AllowOverride None
               Order allow,deny
               allow from all
       </Directory>
       ErrorLog ${APACHE_LOG_DIR}/error.log
       LogLevel warn
       CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
       SSLEngine on
       SSLCertificateFile    /etc/apache2/ssl/ssl.pem
       SSLCertificateKeyFile /etc/apache2/ssl/ssl.key
       <FilesMatch "\.(cgi|shtml|phtml|php)$">
               SSLOptions +StdEnvVars
       </FilesMatch>
       <Directory /usr/lib/cgi-bin>
               SSLOptions +StdEnvVars
       </Directory>
       BrowserMatch "MSIE [2-6]" \
               nokeepalive ssl-unclean-shutdown \
               downgrade-1.0 force-response-1.0
       BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
       <Directory /var/www/subfolder>
               Options Indexes FollowSymLinks MultiViews
               AllowOverride All
               Order allow,deny
               Allow from all
               Satisfy Any
       </Directory>
</VirtualHost>
</IfModule>

我嘗試將重寫條件添加到 default-ssl 文件中,但是當我重新載入配置時,會出現此錯誤:

Reloading web server config apache2                                                                             
[Sat Mar 22 22:57:11 2014] [warn] _default_ VirtualHost overlap on port 443, the first has precedence

所以我刪除了default-ssl。如何讓 apache 接受我的重寫條件?

謝謝,

愛爾蘭共和軍

編輯:

為了讓我的問題更清楚……重新載入錯誤不是我真正的問題,只是為了澄清我到目前為止的嘗試;)

http://example.com <- shows /var/www content = OK
https://sub.example.com <- shows /var/www/sub content = OK
https://example.com <- also shows /var/www/sub content = Not OK, I want this rewritten to https://sub1.example.com

但我不知道如何以及在哪裡編寫此規則。

我的猜測是您RewriteCond的不匹配,因為:

  • 好像RewriteCond不喜歡%{HTTP_HOST} 比較%{HTTP_HOST}
  • %{HTTP_HOST}變數只包含主機(Host Header),沒有前綴https://

你應該試試 :

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule ^(.*)$ https://cloud.%{HTTP_HOST}$1 [R=301,L]

引用自:https://serverfault.com/questions/583915