apache RewriteRule 无法正常工作

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>

答案1

我没有测试它,但我注意到几个(潜在的)问题:

  • RewriteCond "%{HTTP_HOST}%{REQUEST_URI}" "^domain\.local\/?$"
    之前\/可能是个问题。一般来说,没有理由参与,REQUEST_URI因为RewriteCond你又在排队了RewriteRule
  • RewriteRule "^domain\.local\/?$"
    该域不属于那里。RewriteRule匹配REQUEST_URI唯一。
  • https://domain.localHTTPS 配置中缺少 的重写规则。

答案2

解决方案比我想象的要简单得多。您只需将所有 HTTP 重定向到 HTTPS,然后在 443 虚拟主机中处理实际重写,这要感谢 @Hauke Laging,他指出实际重定向应该发生在 443 虚拟主机中,并且我使用的正则表达式中也出现错误。本文如何通过一次重定向强制使用 https、www 和尾随斜杠读起来也很有趣。

<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>

相关内容