https后面的Apache目录尾随斜杠问题

时间:2016-11-05 18:25:38

标签: apache redirect https reverse-proxy

我在https门户后面运行一个apache服务器,并且在目录重定向方面存在问题。 我的apache服务器是一个docker容器,它接收由https门户容器(steveltn / https-portal)转发的请求。 一切正常,除了对http而不是https进行的默认http重定向。例如,假设我的apache网站上有一个名为test的目录。调用https://example.com/test会返回301代码,并重定向到http://example.com/test/。 正确的行为是重定向到https。

我首先想到的是我的https门户网站配置错误,并询问了steveltn / https-portal团队。但他们回答说我的apache配置存在问题(https://github.com/SteveLTN/https-portal/issues/67#issuecomment-257934618)。 答案摘要是

  

PORTAL确实通过请求标头告诉Apache它的存在   X-Forwarded-Proto:https。一些网络应用识别此标题   自动,如WordPress。我想现在由你来决定   配置您的Web应用程序以识别此标题

我尝试了很多在互联网上找到的配置,例如这个配置,但没有一个能解决问题:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</VirtualHost>

如果我将RewriteCond更改为%{HTTP:X-Forwarded-Proto} https,我会得到一个无限重定向循环。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

可能是因为你有一个导致这种重定向的.htaccess文件?

如果问题确实是由上面的配置引起的,您可以尝试以下方法:

RewriteEngine On

# add a trailing slash to all directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301] 

## redirect to https 
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

答案 1 :(得分:1)

在研究Gerfried之后,这里是我使用的解决方案。

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{HTTP:X-Forwarded-Proto} https 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/ [L,R=301]

它适用于以下情况:

  • 请求目录 - &gt; https redirect
  • 请求现有文件 - &GT;提供文件
  • 请求缺少资源 - &gt; http 404错误。

答案 2 :(得分:0)

the mod_rewrite documentation中所述,应使用%{LA-U:REQUEST_FILENAME}格式获取目录名称;这种形式不受所有<Location>,mod_rewrite等路径转换的影响。所以:

RewriteEngine On
RewriteCond %{LA-U:REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{HTTP:X-Forwarded-Proto} https 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/ [L,R=301]