简体   繁体   中英

htaccess redirect to subfolder with a trailing slash

I successfully managed to redirect all requests to a subfolder of my web server.

This is the code I'm using:

/.htaccess

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} !^/public/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /public/$1 [L]

/public/.htaccess

# redirect all urls that doesn’t have a 
# trailing slash to urls with a trailing slash
# (this is my try)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$

RewriteRule ^(.*)$ $1 [NC]

It works perfectly, so the following redirects work:

example.com                 -> example.com/public/
example.com/foo/            -> example.com/public/foo/
example.com/foo/about.html  -> example.com/public/foo/about.html

By the way, the following redirect has a problem:

example.com/foo             -> example.com/public/foo

Although it redirects correctly, the actual URL in the address bar is:

example.com/public/foo/

So my question is:

How can I have a clean URL when redirecting from a URL without a forward slash?

Hope it makes sense.

Place this code in root .htaccess:

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

RewriteCond %{REQUEST_URI} !^/public/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /public/$1/ [L]

Then just remove /public/.htaccess since that is not needed.

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