Sourabh
Sourabh

Reputation: 1765

multiple .htaccess files conflicting with each other

I have a shared hosting with multiple domain hosted on it. In the root folder of my hosting exists a .htaccess (say is htaccess1). Code in ht1 is:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?mydomain.com$ [NC]
RewriteCond %{REQUEST_URI} !^/mydomain/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /mydomain/$1
RewriteCond %{HTTP_HOST} ^(www.)?mydomain.com$ [NC]
RewriteRule ^(/)?$ mydomain/index.php [L]

These rules are there so that only urls with www.mydomain.com use all files of mydomain folder. I am new to url rewriting so I don't understand the meaning of what each line does. Another .htaccess (say htaccess2) file exists in mydomain folder. Code is htaccess2 is:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)?/$ try.php?id=$1
RewriteRule ^([0-9]+)?$ try.php?id=$1
RewriteRule ^post/([0-9]+)?/$ post.php?id=$1
RewriteRule ^post/([0-9]+)?$ post.php?id=$1

In this file, line 6,7 works fine and redirect requests with numeric parameters to try.php but lines 8,9 doesn't work and gives a 404 page not found error, exact error string is :

The requested URL /mydomain/post/1233445 was not found on this server.

I doubt that some effect of htaccess1 is creating this problem as I tried many variations of regex in line 8,9. Please help.

Upvotes: 1

Views: 453

Answers (1)

anubhava
anubhava

Reputation: 785276

Main .htaccess:

Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/mydomain/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /mydomain/$1 [L]

RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com$ [NC]
RewriteRule ^$ /mydomain/index.php [L]

Changes:

  1. Added RewriteBase at the top.
  2. Added L flag to mark it last rule.
  3. Added required options.

mydomain .htaccess:

Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /mydomain/

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteRule ^post/([0-9]+)/?$ post.php?id=$1 [L,QSA,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/?$ try.php?id=$1 [L,QSA]

Changes:

  1. Added RewriteBase at the top.
  2. Added L flag to mark it last rule.
  3. Removed a redundant rule.
  4. Moved specific rule above the generic rule.
  5. Added required options.

Upvotes: 2

Related Questions