user3604203
user3604203

Reputation:

RewriteEngine - How to ignore requests for folders that already exist

What I would like is if the user enters: www.mysite.com/test This would redirect to a page that would search my db for an event called test and if the event exists show the event else redirect to a search page.

I've nearly managed to get this to work - so close yet so far...

This is where I've got to:

RewriteEngine On     
RewriteRule    ^([A-Za-z0-9-]+)/?$    show_events.php?q=$1    [NC,L] 

It works in that it redirects to the show_events.php page which searches the db for an exact match and displays the event if it finds one, else it redirects to a search page. I'm very pleased with this.

The problem is when the folder (www.mysite.co.uk/test/) exists already an error page shows saying "this page isn't working". The folder just contains a HTML page that displays the word "hello". If you type www.mysite.co.uk/test/index.html the page displays ok so it's not like it isn't working.

I've concluded the search page works fine but the RewriteEngine code doesn't.

This post looked like it would solve my problem but not quite: Apache RewriteEngine - Rewrite anything that not exists to index.php

I thought that by adding DPI on the end of the RewriteRule it might solve the problem but it doesn't.

I really don't understand RewriteEngine and am just groping around in the dark using trial and error, can someone help me?

Upvotes: 2

Views: 32

Answers (2)

Amit Verma
Amit Verma

Reputation: 41219

The problem is that your rule also rewrites existent directories to the destination file. You need to put a condition to exclude directories from the rule :

RewriteEngine On
RewriteCond ℅{REQUEST_FILENAME} !-d     
RewriteRule ^([A-Za-z0-9-]+)/?$    show_events.php?q=$1  [NC,L]

The RewriteCondition will prevent your existent directories from being rewritten to the rule's destination url.

Upvotes: 1

Justin Iurman
Justin Iurman

Reputation: 19016

You can simply add a condition to avoid touching existing folders

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9-]+)/?$ /show_events.php?q=$1 [NC,L] 

Upvotes: 1

Related Questions