user1063287
user1063287

Reputation: 10869

how to specify only one directory for an .htaccess rewrite rule?

i had a rewrite rule working fine where any pages in the format site.com/dir/page1.php were translated into the format site.com/page1. i achieved that with:

# 1. turn on the rewriting engine
RewriteEngine On

# 2. remove the www prefix
RewriteCond %{HTTP_HOST} ^www\.site\.com [NC] 
RewriteRule ^(.*)$ http://site.com/$1 [L,R=301]

# 3.  send all non-secure pages to secure pages
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

# 4. if 404 not found error, go to homepage
ErrorDocument 404 /index.php

# 5. if url received with trailing slash (e.g. http://domain/test/) then go to correct page (e.g. http://domain/pages/test.php)
RewriteRule ^([^.]+)/$ includes/$1.php

# 6. if url received WITHOUT trailing slash (e.g. http://domain/test) then go to correct page (e.g. http://domain/pages/test.php)
RewriteRule ^([^.]+)$ includes/$1.php

i have now set up a blog at site.com/blog/ and when i try and visit the blog it is displaying the home page (ie a 404 error).

i think the error is at part #5 and #6 and that somehow i need to specify that the rewrite rule is specifically only for the 'includes' directory? but i could be wrong, any help appreciated, thank you!

update:

i tried the solution to ignore the 'blog' directory here:

How to configure .htaccess file for rewrite rules to get rid of extensions, trailing slashes, www?

#skip wordpress site which starts with blog
RewriteCond %{REQUEST_URI} !^/blog [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

but that didn't work for me unfortunately.

Upvotes: 2

Views: 3322

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270607

To prevent rewriting on the blog/, place the following before your rules 5,6 (which are generi rewrites):

# Do not apply the following to the blog
RewriteCond %{REQUEST_URI} !^/blog

# 5. if url received with trailing slash (e.g. http://domain/test/) then go to correct page (e.g. http://domain/pages/test.php)
# Merged 5 & 6 together by making the trailing slash optional /?
RewriteRule ^([^.]+)/?$ includes/$1.php

Another possibility is to prevent rewriting on any directory that exists:

# Do not apply the following to actual existing files and directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Merged 5 & 6 together by making the trailing slash optional /?
RewriteRule ^([^.]+)/?$ includes/$1.php

Upvotes: 3

Related Questions