Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mod_rewrite to hide .php from the end of URLs

I've got a site where all the pages are php scripts, so the URLs end .php.

I've added the following to a .htaccess file, and I can now access the .php files without the .php extension:

RewriteEngine On  # Turn on rewriting

RewriteCond %{REQUEST_FILENAME}.php -f  # If the requested file with .php on the end exists
RewriteRule ^(.*)$ $1.php #  serve the PHP file

So far so good. But now I want to add a Redirect on all the .php files so that any old links outside of my control get redirected to the new version of the URL.

I've tried this:

RewriteEngine On  # Turn on rewriting

RewriteCond %{REQUEST_URI} .*\.php
RewriteRule ^(.*)\.php$ http://example.com/$1 [R=permanent,L]

RewriteCond %{REQUEST_FILENAME}.php -f  # If the requested file with .php on the end exists
RewriteRule ^(.*)$ $1.php [L] #  serve the PHP file

but that seems to send a redirect even for URLs that don't end in .php, so I get stuck in an infinite loop. Any other combination I try seems to match no requests (and leave me at page.php) or all requests (and get me stuck in a loop).

like image 616
rjmunro Avatar asked Jun 21 '10 16:06

rjmunro


People also ask

What is PHP mod_rewrite?

The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly. By default, mod_rewrite maps a URL to a filesystem path. However, it can also be used to redirect one URL to another URL, or to invoke an internal proxy fetch.

How does mod rewrite work?

mod_rewrite works through the rules one at a time, processing any rules that match the requested URL. If a rule rewrites the requested URL to a new URL, that new URL is then used from that point onward in the . htaccess file, and might be matched by another RewriteRule further down the file.

What is Rewriteengine on htaccess?

htaccess rewrite rules can be used to direct requests for one subdirectory to a different location, such as an alternative subdirectory or even the domain root. In this example, requests to http://mydomain.com/folder1/ will be automatically redirected to http://mydomain.com/folder2/.


1 Answers

RewriteEngine On

RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php(\?.*)?\ HTTP/
RewriteRule ^ http://%{HTTP_HOST}/%1 [R=301]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .* $0.php

Only %{THE_REQUEST} is not rewritten in the internal redirection that happens in the second rule (%{REQUEST_URI}, on the other hand, is).

like image 165
Artefacto Avatar answered Oct 05 '22 22:10

Artefacto