问题
I run an apache server behind an https portal and have an issue with directory redirection. My apache server is a docker container that receives requests forwarded by an https portal container (steveltn/https-portal). Everything works fine, except the default http redirections that are made to http instead of https. For instance, let say we have a directory named test in my apache website. Calling https://example.com/test returns a 301 code with redirection to http://example.com/test/. The right behaviour would be to have a redirection to https.
I first thought it was a misconfiguration of my https portal, and asked steveltn/https-portal team. But they replied it's a problem in my apache configuration (https://github.com/SteveLTN/https-portal/issues/67#issuecomment-257934618). The summary of the answer is
PORTAL does tell the Apache about its existence by the request header X-Forwarded-Proto: https. Some web apps recognize this header automatically, such as WordPress. I guess now it up to you to configure your web app to recognize this header
I tried a lot of configuration found on the Internet for instance this one, but none fixes the problem:
<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>
If I change the RewriteCond to %{HTTP:X-Forwarded-Proto} https, I get a infinite redirection loop.
Any idea ?
回答1:
Might it be that you have an .htaccess file which causes this redirect?
If the problem is really caused by the config above, you could try the following:
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]
回答2:
After working on Gerfried proposal here is the solution I use.
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]
It works in the following situations:
- Request to a directory -> https redirect
- Request to an existing file -> serves the file
- Request to a missing resource -> http 404 error.
回答3:
As documented in the mod_rewrite documentation one should use the %{LA-U:REQUEST_FILENAME}
form to get at the directory name; this form is immune to all <Location>
, mod_rewrite etc. path translations. So:
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]
来源:https://stackoverflow.com/questions/40441717/apache-directory-trailing-slash-issue-behind-https