Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mod_rewrite: how to redirect everything except 2 files to "/"?

I have a bit of a problem with a mod_rewrite configuration.

I want to redirect everything to the root directory (http://www.mydomain.com/), except for two files.

So I tried this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !^/
RewriteCond %{REQUEST_FILENAME} !/file1.html
RewriteCond %{REQUEST_FILENAME} !/file2.html
RewriteRule ^(.*)$ http://www.mydomain.com/ [L,R=301]

This unfortunetely doesn't redirect anything.

If I leave out the first RewriteCond line, I get a redirection error.

Where did I go wrong here?

like image 856
Oliver Cyberpagan Krapp Avatar asked Dec 05 '25 07:12

Oliver Cyberpagan Krapp


1 Answers

First, you'll probably want to use REQUEST_URI instead of REQUEST_FILENAME. They may be the same in a virtual host scenario, but not normally. You're probably meaning to rewrite the URI, not the local path.

Secondly, your rule;

RewriteCond %{REQUEST_FILENAME} !^/

...excludes all requests to something starting with /, that is all URIs, from being rewritten. What you'll want to do is probably;

RewriteCond %{REQUEST_URI} !^/$

The rules for the ignored files should probably have an additional $ at the end to be an "ends with" match instead of a "contains" match.

That leaves something like;

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_URI} !/file1.html$
RewriteCond %{REQUEST_URI} !/file2.html$
RewriteRule ^(.*)$ http://www.mydomain.com/ [L,R=301]
like image 164
Joachim Isaksson Avatar answered Dec 07 '25 05:12

Joachim Isaksson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!