The following code works to hide .php and replace it with .html
RewriteEngine ON
RewriteCond %{REQUEST_URI} ^/([^/]*)/([^.]*).html/?$ [NC]
RewriteRule ^(.*)$ %1/%2/index.php [L]
I would like to redirect all .php requests to .html.
All .php files are inside a sub directory in "https://www.sitename.com/user/".
For example
https://www.sitename.com/user/login/index.php
https://www.sitename.com/user/name/index.php
https://www.sitename.com/user/register/index.php
https://www.sitename.com/user/logout/index.php
https://www.sitename.com/user/dashboard/index.php
https://www.sitename.com/user/contact/index.php
It should redirect to
https://www.sitename.com/user/login.html
https://www.sitename.com/user/name.html
https://www.sitename.com/user/register.html
https://www.sitename.com/user/logout.html
https://www.sitename.com/user/dashboard.html
https://www.sitename.com/user/contact.html
Adding separate line of .htaccess code for each folder will be difficult, can someone help with simple code to automatically detect and redirect .php to .html ?
Explanation:
If some try to access "sitename.com/user/login/index.php
", it should load "sitename.com/user/login.html
".
sitename.com/user/login.html
should be the only URL that is visible to users. Even if someone try to access "sitename.com/user/login/index.php
", it should redirect/rewrite to "sitename.com/user/login.html
".
Enter sitename.com/user/login.html
in browser = sitename.com/user/login.html
Enter sitename.com/user/login/index.php
in browser = sitename.com/user/login.html
2
Answers
With your shown samples, could you please try following. Please make sure you clear your browser cache before validating your URLs. As per OP’s comment edited rules, as per
.php
and.html
formats. I believe you should avoid giving both kind of urls to users and ask them to hit only .html urls in case anyone hits.php
url you could forbid it(in case they are directly hitting it, another reason could be because if they are hitting.php
directly then you want it to change URL on browser to .html which is actually being served by a.php
file itself in backend), if they hit .html then that could be served by respective index.php of passed uri IMHO. NOTE: This is IMHO only and should not be used if someone has more requirements on this one.You can use the following rules to convert your
php
URLs intohtml
:The rule #1) triggers when
/user/foobar/index.php
is requested and redirects it to/user/foobar.html
. Since the.html
file doesn’t exist the second rule maps the.html
request back to original.php
page but your URL remains the same in browser address bar.