.htaccess - Rewrite multiple subdirectories to roo

2019-05-05 07:48发布

问题:

I am trying to rewrite multiple subdirectories to the root directory. The situation I have it that I have one folder named blog/ which would contain the main site folder and also another subdirectory called projects/ containing other folders which I want accessible from the root:

www/
    blog/
        work/
        contact/
    projects/
        projectA/
        projectB/

What I want, is to be able to access work/, contact/, projectA/ and projectB/ from the root directory by going to example.com/projectA or example.com/projectB for example. I would also like the blog/ directory to take priority in the case that a folder exists in both.

Currently, in my htaccess, I have this, though it just rewrites everything to blog/, removing this from the URL, though not affecting the projects/ folder.

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_URI} !(.*)site
RewriteRule ^(.*)$ site/$1 

回答1:

Try:

RewriteEngine on

# first check if request is in /blog/
RewriteCond %{DOCUMENT_ROOT}/blog%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/blog%{REQUEST_URI} -d
RewriteRule ^(.*)$ /blog/$1 [L]

# then check if request is in /projects/
RewriteCond %{DOCUMENT_ROOT}/projects%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/projects%{REQUEST_URI} -d
RewriteRule ^(.*)$ /projects/$1 [L]

# otherwise, blindly rewrite to blog (or do nothing by removing this rule to allow a 404 not found)
RewriteCond ${REQUEST_URI} !^/blog/
RewriteRule ^(.*)$ /blog/$1 [L]