Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess redirect .php and .html requests

I work with a framework called SilverStripe ... we are currently in the process of migrating an old site onto this framework. The problem is that the old site URLs ended with .php or .html whilst in the new site they don't.

I need to amend the second rewrite rule in such a way that I pump the request to main.php without any .html or .php extensions.

In my current .htaccess I have the following rules:

# Turn off index.php handling requests to the homepage fixes issue in apache >=2.4
<IfModule mod_dir.c>
    DirectoryIndex disabled
</IfModule>

SetEnv HTTP_MOD_REWRITE On
RewriteEngine On

# Enable HTTP Basic authentication workaround for PHP running in CGI mode
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Deny access to potentially sensitive files and folders
RewriteRule ^vendor(/|$) - [F,L,NC]
RewriteRule silverstripe-cache(/|$) - [F,L,NC]
RewriteRule composer\.(json|lock) - [F,L,NC]

# Process through SilverStripe if no file with the requested name exists.
# Pass through the original path as a query parameter, and retain the existing parameters.
RewriteCond %{REQUEST_URI} ^(.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* framework/main.php?url=%1 [QSA]

# If framework isn't in a subdirectory, rewrite to installer
RewriteCond %{REQUEST_URI} ^(.*)/framework/main.php$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . %1/install.php? [R,L]

Possible solution (still testing):

 RewriteCond %{REQUEST_URI} ^(.*)\.html [OR]
 RewriteCond %{REQUEST_URI} ^(.*)\.php [OR]
 RewriteCond %{REQUEST_URI} ^(.*)$
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule .* framework/main.php?url=%1 [QSA]
like image 589
Gabriel Spiteri Avatar asked Dec 29 '15 10:12

Gabriel Spiteri


1 Answers

Add the following rules to your .htaccess file below the # Deny access to potentially sensitive files and folders block of rules:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^(.+)\.html$
RewriteRule (.*)\.html$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^(.+)\.php$
RewriteRule (.*)\.php$ /$1 [R=301,L]

The first two lines check that the url is not a directory and is not file.

The third line checks that the url contains either .html or .php.

The forth line removes .html / .php from the url

like image 184
3dgoo Avatar answered Sep 29 '22 15:09

3dgoo