Apache-Httpd

apache RewriteRule 無法正常工作

  • July 12, 2020

我正在嘗試使用 Apache 執行以下操作:

如果我要求 http(s)://domain.local(/) 我應該被重定向到一個全新的域,例如 https://www.domain_new.local

如果我要求http://domain.local/gp>我應該被重定向到<https://domain.local/gp

我嘗試了以下方法,但似乎不起作用:

&lt;VirtualHost *:80&gt;
   ServerName domain.local

   DocumentRoot "/var/www/html/"
   
   # html directory contains gp directory 
   &lt;Directory /var/www/html&gt;
       Options FollowSymLinks
       AllowOverride All
       Require all granted
   &lt;/Directory&gt;
   
   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"
&lt;/VirtualHost&gt;


&lt;VirtualHost *:443&gt;
   ServerName domain.local

   DocumentRoot "/var/www/html/" 
   
   SSLEngine on
   
   # html directory contains gp directory     
   &lt;Directory /var/www/html&gt;
       Options FollowSymLinks
       AllowOverride All
       Require all granted
   &lt;/Directory&gt;
   
   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
&lt;/VirtualHost&gt;

解決方案比我想的要簡單得多。您只需將所有 HTTP 重定向到 HTTPS,然後在 443 虛擬主機中處理實際重寫,這要感謝@Hauke Laging,他指出實際重定向應該發生在 443 虛擬主機中,並且我使用的 RegEx 中也會出現錯誤。這篇文章How to force https, www and a trailing slash with one redirect也很有趣。

&lt;VirtualHost *:80&gt;
   ServerName domain.local

   DocumentRoot "/var/www/html/"
   
   # html directory contains gp directory 
   &lt;Directory /var/www/html&gt;
       Options FollowSymLinks
       AllowOverride All
       Require all granted
   &lt;/Directory&gt;
   
   RewriteEngine on
   RewriteCond %{HTTPS} off
   RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
&lt;/VirtualHost&gt;


&lt;VirtualHost *:443&gt;
   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     
   &lt;Directory /var/www/html&gt;
       Options FollowSymLinks
       AllowOverride All
       Require all granted
   &lt;/Directory&gt;
   
   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
&lt;/VirtualHost&gt;

我沒有測試它,但我注意到幾個(潛在的)問題:

  • RewriteCond "%{HTTP_HOST}%{REQUEST_URI}" "^domain\.local\/?$"
    \之前的 可能/有問題。一般來說,沒有理由參與REQUEST_URIRewriteCond因為您RewriteRule再次參與其中。
  • RewriteRule "^domain\.local\/?$"

該域不屬於那裡。RewriteRule匹配REQUEST_URI唯一。

  • https://domain.localHTTPS 配置中缺少的重寫規則。

引用自:https://unix.stackexchange.com/questions/597777