虚拟主机反向代理中的mod_rewrite

时间:2018-08-14 08:47:33

标签: mod-rewrite reverse-proxy virtualhost

我在端口443上Apache 2.4之后的8080端口上使用Tomcat。我已经在Apache虚拟主机上设置了通常的反向代理配置,可以正常工作。这是我的设置:

<VirtualHost *:443>
    ServerName www.example.com
    ServerAlias www.example.com
    ServerAdmin admin@example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    ProxyRequests Off
    <Proxy *>
      Order deny,allow
      Allow from all
    </Proxy>
    ProxyPass / http://example.com:8080/
    ProxyPassReverse / http:example.com:8080/
    <Location />
      Order allow,deny
      Allow from all
    </Location>
    SSLEngine on
    SSLCertificateFile /etc/ssl/example.com.crt
    SSLCertificateKeyFile /etc/ssl/example.com.key
    SSLCertificateChainFile /etc/ssl/CA.crt

    RewriteEngine On
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
    LogLevel alert rewrite:trace6
    RewriteRule ^post$ post.xhtml [NC]
</VirtualHost>

我想在Apache上使用mod_rewrite,但是,这似乎不起作用。我意识到在.htaccess上进行重写(不适用于我的情况)时,重写规则可以正常工作。但是,当我从虚拟主机尝试相同的规则时,它不起作用。例如,使用以下规则:

RewriteEngine on
LogLevel alert rewrite:trace6
RewriteRule ^test$ test.php [QSA]

我从错误日志中收到404错误,内容如下:

[Tue Aug 14 12:12:40.135059 2018] [rewrite:trace2] [pid 11554] mod_rewrite.c(482): [client 127.0.0.1:53326] 127.0.0.1 - - [localhost/sid#7efc776e9518][rid#7efc776710a0/initial] init rewrite engine with requested uri /test
[Tue Aug 14 12:12:40.135108 2018] [rewrite:trace3] [pid 11554] mod_rewrite.c(482): [client 127.0.0.1:53326] 127.0.0.1 - - [localhost/sid#7efc776e9518][rid#7efc776710a0/initial] applying pattern '^test$' to uri '/test'
[Tue Aug 14 12:12:40.135121 2018] [rewrite:trace1] [pid 11554] mod_rewrite.c(482): [client 127.0.0.1:53326] 127.0.0.1 - - [localhost/sid#7efc776e9518][rid#7efc776710a0/initial] pass through /test

可能缺少什么?我希望可以在.htaccess上重写规则

1 个答案:

答案 0 :(得分:0)

这是解决方案;首先,.htaccess不适用。根据文档,服务器配置和<虚拟主机是适用的mod_proxy的上下文(在我们的情况下,.htaccess还是没有意义)。

解决方案是使用带有标志P的重写规则,这将导致该请求由mod_proxy处理,并通过代理请求进行处理。查看更多here

虚拟主机应进行如下修改:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^/post/(.*)$ post.xhtml\?id=$1 [P]
ProxyPass / http://example.com:8080/
ProxyPassReverse / http:example.com:8080/
相关问题