Laim McKenzie Laim McKenzie - 2 months ago 13
Apache Configuration Question

.htaccess conflict while removing extension

OK. So I'm currently making a website to show images. (Kinda like Imgur I guess), and the normal URL is /n?=image, now I have a rewrite to change that to /image, which works fine.

I also have a Privacy Policy, ToS and Contact pages which I would like to remove the extensions from (.php). The Privacy Policies page works fine, as that file is in a Directory called "policies". So it removes the .php extension without a hassle.

When I go to /contact however, it redirects it thinking it is an image. Is it possible to have the removal of the .php extension, as well as redirecting images at the same time? I had a search on here but couldn't find anything relating to this issue that helped.

# Snapr Rewrites
RewriteBase /
RewriteRule ^([a-zA-Z0-9]+)$ index.php?n=$1
RewriteRule ^([a-zA-Z0-9]+).png$ index.php?n=$1
RewriteRule ^([a-zA-Z0-9]+)$ ^([a-zA-Z0-9]+).png$

# Remove .PHP from URL's
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]


EDIT:



Basically. I'm wanting to have:

http://example.com/?n=image
turn into
http://example.com/image


http://example.com/contact.php
turn into
http://example.com/contact

Answer

You should check for existence of .php file before adding .php for a request and more importantly keep .php adding rule before other image rule:

RewriteEngine On
RewriteBase /

# add .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# handle images
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]+)(?:\.png)?$ index.php?n=$1 [L,QSA]