简体   繁体   中英

Remove trailing slash in .htaccess for CloudFront use

There are plenty of 'remove trailing slash' bits of regex here on StackOverflow, and they're all lovely, but they all have the same issue: they don't work too well with a CDN service like Amazon CloudFront.

So, my setup is that www.example.com is Amazon Cloudfront, while my real website is, say, on real.example.com.

All the three below will happily remove trailing slashes from www.example.com/directory/ but will rewrite the URL as real.example.com/directory which clearly I don't want.

I've used

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ %{REQUEST_URI} [R=301,L]

or

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

or

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ /$1 [R=301,L]

...but all of these will expose the 'real' domain name.

How can I write a regex rewrite rule that will correctly remove the trailing slash but not rewrite the domain to the origin website?

(I don't mind hard-coding the domain URL in here, but I need to keep the http or https bit intact.)

Did you try something like this?

# Set "protossl" to "s" if we were accessed via https://. This is used later
RewriteRule ^ - [E=protossl]
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=protossl:s]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ http%{ENV:protossl}://www.example.com/$1 [R=301,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM