简体   繁体   中英

How do I redirect with htaccess all but 1 directory and 1 file?

Here's my setup. I have example.com, which has files and subdirectories. One of those files is maintenance.php and one of those directories is /admin. I'm trying to redirect all requests from example.com to example.com/maintenance.php EXCEPT for example.com/maintenance.php (not doing so causes an error) and all pages in example/admin. example.com/file1 should redirect to example.com/maintenance.php, example.com/maintenance.php should not cause any errors, and example.com/admin/file1 should NOT redirect.

This is what I have that I couldn't get to work:

RewriteEngine On
RewriteCond %{REQUEST_URI} !(.*)admin.*
RewriteCond %{REQUEST_URI} !^/maintenance.php$
RewriteRule .* /maintenance.php [R=302,L]

example.com/admin still redirects to example.com/maintenance.php

Thanks all

Never use an external redirect when your site is unavailable; you need to set a 503 header or you might kill your search engine ranking.

Leave any existing rewrite rules alone, and add this before all of them:

RewriteRule ^(?!maintenance\.php$|admin(?:$|/)) maintenance.php [NS,L]

The first lines of maintenance.php should be

<?php
header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');

It can still have content.

If you still can't get into admin, you'll at least be able to see what other URLs need whitelisting. You might need to exclude media, css and/or js directories, too.

When you're done, comment out the rule with a # for next time.

Make sure your example.com/admin URL is not a 404 Not Found. When the server tries to redirect to the Error Document, it will then redirect to maintenance.php because the Error Document is not excluded from the redirect. To avoid this, you could add a RewriteCond rule that excludes your error documents. For example:

RewriteEngine On

#Exclude *admin* and /maintenance.php
RewriteCond %{REQUEST_URI} !.*admin.*
RewriteCond %{REQUEST_URI} !^/maintenance\.php$

#This handles both 404 and 500 Errors
RewriteCond %{REQUEST_URI} !^/path/to/(404|500)\.html$

RewriteRule .* /maintenance.php [R,L]

I also escaped the dots in the paths, as it is good practice to do so. (Avoids maintenanceXphp not redirecting as well.)

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