bamya
bamya

Reputation: 416

htaccess configuration to remove extension with directory structure

I am new to server configurations and having some hard times with htaccess configuration. I am using this htaccess to work without .php extensions and at the same time if user has entered .php at the end it also removes that part and shows a more clear url. At the end section I am handling errors with error.php

RewriteEngine On

# 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]

ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php

Every thing works great on pages at root, such as

example.com/contact

But things are getting complicated inside the folders, such as

example.com/photo/views

Here rather than showing the "/photo/views.php", I am getting 404 page not found and seeing my error page.

But I can see index page under photo directory as.

example.com/photo/

But still get error page on

example.com/photo/index

If I delete .htaccess file everything works fine with the .php extension in the end.

I would be glad if someone can show me what I am doing wrong.

Upvotes: 1

Views: 71

Answers (2)

anubhava
anubhava

Reputation: 785266

You need to remove / from exclusion character class in 2nd rule and tweak your regex a bit:

ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php
RewriteEngine On

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

# Redirect external .php requests to extension-less url
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=302,L,NE]

# Resolve .php file for extension-less php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]

Upvotes: 1

Mike Rockétt
Mike Rockétt

Reputation: 9007

Your rule states that forward slashes are not allowed in the request URI. As such, the rewrite will not work.

Change your rule to:

RewriteRule ^([^.]+)$ $1.php [L]

I have removed the forward slash from the expression so that it now only disallows periods (.).

Upvotes: 2

Related Questions