Rodrigo
Rodrigo

Reputation: 5129

.htaccess rewrite rule with existing directory

I have the following .htaccess file on my website root

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([^/]+)/?$ /index.php?t=$1 [L]

It means that, for some links like

www.website.com/foo
www.website.com/bar

it will be internally replaced by

www.website.com/index.php?t=foo
www.website.com/index.php?t=bar

Problem is: one of this directories (say, bar) exists, and I want to be able to use the link www.website.com/bar/file.pdf, so I had to modify .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?([^/]+)/?$ /index.php?t=$1 [L]

I removed the line ending in !-d, which means “if the directory doesn’t exist”. But now I see

www.website.com/bar/index.php?t=bar

So how can I have both

www.website.com/bar
www.website.com/bar/file.pdf

with the first redirecting (internally) to www.website.com/index.php?t=bar and the second pointing to the right file?

Upvotes: 0

Views: 60

Answers (1)

jacouh
jacouh

Reputation: 8741

You could try this if /bar/index.php exists:

RewriteEngine On

#
# rule 1
#
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . %{REQUEST_FILENAME}/index.php [QSA,L]

#
# rule 2
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([^/]+)/?$ /index.php?t=$1 [L]

This way if directory /bar/ exists, it's rewritten definitively by the first rule 1 to /bar/index.php. At the same time, /bar/file.pdf will not be touched as the file exists.

Upvotes: 1

Related Questions