Apache-Httpd
apache RewriteRule 無法正常工作
我正在嘗試使用 Apache 執行以下操作:
如果我要求 http(s)://domain.local(/) 我應該被重定向到一個全新的域,例如 https://www.domain_new.local
如果我要求http://domain.local/gp>我應該被重定向到<https://domain.local/gp
我嘗試了以下方法,但似乎不起作用:
<VirtualHost *:80> ServerName domain.local DocumentRoot "/var/www/html/" # html directory contains gp directory <Directory /var/www/html> Options FollowSymLinks AllowOverride All Require all granted </Directory> RewriteEngine on RewriteCond "%{HTTP_HOST}%{REQUEST_URI}" "^domain\.local\/?$" RewriteRule "^domain\.local\/?$" "https://domain_new.local" RewriteCond "%{HTTP_HOST}%{REQUEST_URI}" "^domain\.local\/gp(.*)" RewriteRule "^/?(.*)" "https://%{SERVER_NAME}/$1" </VirtualHost> <VirtualHost *:443> ServerName domain.local DocumentRoot "/var/www/html/" SSLEngine on # html directory contains gp directory <Directory /var/www/html> Options FollowSymLinks AllowOverride All Require all granted </Directory> SSLCertificateFile /etc/pki/tls/certs/domain.local.crt SSLCertificateKeyFile /etc/pki/tls/private/domain.local.key SSLCertificateChainFile /etc/pki/tls/certs/domain.local.ca-bundle </VirtualHost>
解決方案比我想的要簡單得多。您只需將所有 HTTP 重定向到 HTTPS,然後在 443 虛擬主機中處理實際重寫,這要感謝@Hauke Laging,他指出實際重定向應該發生在 443 虛擬主機中,並且我使用的 RegEx 中也會出現錯誤。這篇文章How to force https, www and a trailing slash with one redirect也很有趣。
<VirtualHost *:80> ServerName domain.local DocumentRoot "/var/www/html/" # html directory contains gp directory <Directory /var/www/html> Options FollowSymLinks AllowOverride All Require all granted </Directory> RewriteEngine on RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </VirtualHost> <VirtualHost *:443> ServerName domain.local DocumentRoot "/var/www/html/" RewriteEngine on RewriteCond "%{HTTP_HOST}%{REQUEST_URI}" "^domain\.local\/?$" RewriteRule .* https://domain_new.local SSLEngine on # html directory contains gp directory <Directory /var/www/html> Options FollowSymLinks AllowOverride All Require all granted </Directory> SSLCertificateFile /etc/pki/tls/certs/domain.local.crt SSLCertificateKeyFile /etc/pki/tls/private/domain.local.key SSLCertificateChainFile /etc/pki/tls/certs/domain.local.ca-bundle </VirtualHost>
我沒有測試它,但我注意到幾個(潛在的)問題:
RewriteCond "%{HTTP_HOST}%{REQUEST_URI}" "^domain\.local\/?$"
\
之前的 可能/
有問題。一般來說,沒有理由參與REQUEST_URI
,RewriteCond
因為您RewriteRule
再次參與其中。RewriteRule "^domain\.local\/?$"
該域不屬於那裡。
RewriteRule
匹配REQUEST_URI
唯一。
https://domain.local
HTTPS 配置中缺少的重寫規則。