Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use .htaccess to hide .php URL extensions?

I want something to put in my .htaccess file that will hide the .php file extension for my php files, so going to www.example.com/dir/somepage would show them www.example.com/dir/somepage.php.

Is there any working solution for this? My site uses HTTPS, if that matters at all.

This is my .htaccess at the moment:

RewriteEngine On

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

ErrorDocument 404 /error/404.php

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]
like image 952
Markum Avatar asked Apr 05 '12 11:04

Markum


People also ask

How do I hide a website extension?

You can now link any page inside the HTML document without needing to add the extension of the page as no extension will be visible now in the URL of the website. The search engine may index these pages as duplicate content, to overcome this add a <canonical> meta tag in the HTML file.


2 Answers

Use this code in your .htaccess under DOCUMENT_ROOT:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L,NE]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

It should be noted that this will also effect all HTTP requests, including POST, which will subsequently effect all requests of this kind to fall under this redirection and may potentially cause such requests to stop working.

To resolve this, you can add an exception into the first RewriteRule to ignore POST requests so the rule is not allowed to them.

# To externally redirect /dir/foo.php to /dir/foo excluding POST requests
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L,NE]
like image 150
anubhava Avatar answered Oct 19 '22 07:10

anubhava


Remove php extension

You can use the code in /.htaccess :

RewriteEngine on


RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_FILENAME}.php [NC,L]

With the code above, you will be able to access /file.php as /file

Remove html extension

RewriteEngine on


RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_FILENAME}.html [NC,L]

Note : 'RewriteEngine on' directive should be used once at top per htaccess, so if you want to combine these 2 rules just remove the line from second rule. You can also remove any other extensions of your choice, just replace the .php with them on the code.

Happy htaccessing!

like image 37
Amit Verma Avatar answered Oct 19 '22 05:10

Amit Verma