James
James

Reputation: 4783

htaccess rewrite, how to negate sub directory files

I have htaccess file performing URL rewrite. It basically removes the .php extension.

The rules work fine, e.g. they successfully rewrite http://example.com/contact.php into http://example.com/contact

However the rewrite also changes sub directory files, such as /includes/check-form-input.php.

So when, for example, a form at contact.php attempts to submit to /includes/check-form-input.php the htaccess rewrite strips the .php from the end and I get 404 headers.
i.e. /includes/check-form-input is not found.

At least that's what appears to happen, using HTTP_REFERER seems to confirm this as the referer was /includes/check-form-input without the ext .php

Is there a way to add a rule to negate all sub dirs?

I have the following htaccess - which is copied from another answer here on SO, as I don't 100% grasp the rewrite structure.
(I've left in the www to non-www redirect in case it's the cause)

## Rewrite on
RewriteEngine on


## Redirect all pages from non-www to www
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]


## URL rewrite
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/$1 [R=301,L]

# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]

Upvotes: 0

Views: 355

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

You can either exclude all subdirectories,

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^([^/]+)\.php$ http://example.com/$1 [R=301,L]

or limit it to only GET requests:

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ (.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/$1 [R=301,L]

or just exclude the includes subdirectory

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteCond %{REQUEST_URI} !^/includes/
RewriteRule ^([^/]+)\.php$ http://example.com/$1 [R=301,L]

Upvotes: 1

Related Questions