Redirect all requests to subdirectory except a few

2019-02-20 15:32发布

问题:

This question attempts to combine knowledge gained from some previous answers on SO, so do not mark as a duplicate unless the answer is meets the all of criteria about to be given.

This is what I want to do:
I need to temporarily .htaccess redirect visitors to my site to a clone copy so that I can make modifications on the existing site.
Therefore, I have the following needs:
1. All users requests /(.*) should be redirected to sub-directory /website/$1 (ie if someone requests /index.php it should go to /website/index.php)
2. If the user is from one of three specific ips the request should not be redirected, and should go to the file (ie if I request /index.php it should go to /index.php)
3. Said redirection should also force the use of www (ie requests with or without www, should be redirected to www.example.com/website)
4. Said redirection should be a temporary redirect of some sorts (the normal site will only be down for a couple of days)

This is my current code:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^/?$ "http\:\/\/www\.example\.com\/website\/" [R=301,L]

It meets criteria 1,3, and 4. I just need help adjusting it to not redirect the three specific ip addresses.

Any thoughts as to how to incorporate #2?

回答1:

How about:

RewriteEngine On

# for #2
RewriteCond %{REMOTE_ADDR} !123\.45\.67\.89$
RewriteCond %{REMOTE_ADDR} !123\.45\.67\.90$

# for #1 and #3 and #4
RewriteCond %{REQUEST_URI} !^/website/ [NC]
RewriteRule ^(.*)$ http://www.example.com/website/$1 [R=302,L]

For #2 you want to replace the 123\.45\.67\.89 etc with the IP addresses that you want not to be redirected.

For #4, the R=301 needed to be changed to R=302