0

I've used htaccess to remove extensions or redirect, such as;

RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteRule ^(.*)/$ /$1.php [L]

I was wondering if anyone has used to it in this way:

If file extension can't be found, check for html or php file under the same name re-direct to file exith extension.

I can only find examples for redirection, file-extension removal and adding trailing slashes to the file, not to do something like my example, any ideas?

1 Answer 1

3

Try this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

# see if .php file can be found with same name
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]

# now see if .html file can be found with same name
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.+?)/?$ /$1.html [L]
Sign up to request clarification or add additional context in comments.

6 Comments

That's perfect @anubhava thanks for the help again, you always seem to help me when its a rewrite or htaccess problem!
I've tried adding code to then remove the displaying extentions but it hasn't worked, how would you suggest I do it?
I actually wanted it to do the above but then remove the extention.
Just to clarify. Let's say you have 2 files in DocumentRoot. 1. contact.php and 2. foo.html then above rules will allow you to have links like 'domain.com/contact` and 'domain.com/foo`
Ok with that code in place, and with those files contact.php, trying to access /contact does nto work and throws up my custom 404 page.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.