Thamilhan
Thamilhan

Reputation: 13313

htaccess redirect fails to redirect when directory exists

For making friendly URLs, Following is the htaccess code applied:

RewriteEngine On

RewriteCond %{THE_REQUEST} /.+?\.php[\s?] [NC]
RewriteRule ^ - [F]

RewriteRule    ^([^/\.]+)$    index.php?id1=$1    [NC,L,QSA]  
RewriteRule    ^([^/\.]+)/([^/\.]+)$    index.php?id1=$1&id2=$2    [NC,L,QSA] 

This now works for:

  1. mydomain.com/pages to mydomain.com/index.php?id1=pages

  2. mydomain.com/pages/xyz to mydomain.com/index.php?id1=pages&id2=xyz

also, when I enter mydomain.com/index.php?id1=pages&id2=xyz manually in the URL, it redirects to mydomain.com.

Now, when I enter another like mydomain.com/templates where templates is a directory that exists, it redirects to mydomain.com/templates/?id1=templates

I tried adding these lines but in vain:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]

My directory structure:

www/
    .htaccess
    index.php  <--- main router
    templates/
            img/
            css/
            ...
            ...
    other_directories/
    ...
    ...

index.php should receive id1 and id2.

How shall I avoid this condition (when directory with that name exists) using htaccess?

Note: This question is already asked here. But posting again, as it didn't gain considerable views nor answered the issue!

Upvotes: 1

Views: 95

Answers (3)

anubhava
anubhava

Reputation: 785146

You should force a trailing slash in front of directories using a redirect rule:

RewriteEngine On

RewriteCond %{THE_REQUEST} /.+?\.php[\s?] [NC]
RewriteRule ^ - [F]

# add a trailing slash to directories
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,R=302]

RewriteRule ^([^/.]+)/?$ index.php?id1=$1 [L,QSA]

RewriteRule ^([^/.]+)/([^/.]+)/?$ index.php?id1=$1&id2=$2 [L,QSA] 

Upvotes: 1

Amit Verma
Amit Verma

Reputation: 41219

If /templates is an existent dir, you can exclude it using a RewriteCond

RewriteCond %{REQUEST_URI} !^/templates [NC]
RewriteRule    ^([^/\.]+)$    index.php?id1=$1    [NC,L,QSA]

or you can use the following rule before your other rules to pass the uri unchanged:

RewriteRule ^templates - [L]  

Upvotes: 0

J.K
J.K

Reputation: 1374

Note: Never Tested

RewriteEngine On

# If the director's are static     
# Redirect exclude for templates, also can add the aonther directory's
RewriteRule ^(templates|another_directory)($|/) - [L]    

# Redirect General
RewriteRule ^([a-zA-Z0-9-/]+)/([a-zA-Z0-9-/]+)$ index.php?id1=$1&id2=$2 [L]
RewriteRule ^([a-zA-Z0-9-/]+)/([a-zA-Z0-9-/]+)/ index.php?id1=$1&id2=$2 [L]
RewriteRule ^([a-zA-Z0-9-/]+)/$ index.php?id1=$1 [L]

Result

mydomain.com/pages/ = mydomain.com/index.php?id1=1

mydomain.com/pages/xyz = mydomain.com/index.php?id1=pages&id2=xyz

It wont redirect for mydomain.com/templates/ and mydomain.com/another_directory/

Upvotes: 0

Related Questions