Kirk Ouimet
Kirk Ouimet

Reputation: 28364

.htaccess Conditional Redirect When Pattern Does Not Match

I want to enable my users to enter search queries using a URL like this:

www.domain.com/searchterm

or with a trailing slash like this:

www.domain.com/searchterm/

However, I want to capture certain search terms and redirect them to an actual directory. For example, a query like this:

www.domain.com/css/site.css

should actually point to the CSS file, and should not pass "css/site.css" as the search term.

Here's my non working code:

RewriteRule ^/(.+)/?$ /index.php?search=$1 [L]
RewriteRule ^/css/(.+)$ /css/$1 [L]

This doesn't work - can anyone tell me what I'm doing wrong?

Upvotes: 0

Views: 1226

Answers (2)

Jeff Rupert
Jeff Rupert

Reputation: 4840

It's not working because your expression isn't written well.

First, if you flip those two it should work fine. Second, take a look at your first RewriteRule. Your expression is ^/(.+)/?$. Basically, it's matching ANYTHING until the end of the string, so long as it starts with /.

If I were working on this file, I'd move the "search" RewriteRule to the end of the file. It would be interpreted last, and therefore it has less a chance of being used.

And as I'm writing this, I see Rick's option, which is what I would do even more than my own option. I'm not too familiar with the RewriteCond yet. What his does is it checks to see if the request is a file or a directory, and if not, it would then go make the search.

Cheers!

Upvotes: 0

Wolph
Wolph

Reputation: 80031

Instead of excluding all your existing urls it would be a far better solution to use a script like thia as a 404 page. While capturing the 404 you could still send a 200 response but atleast it would make your rewrite rules far easyer.

Or if you really want to do it without the 404, use this

RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule .? /search_script [L]

Upvotes: 1

Related Questions