Home > Software design >  What is the right htaccess code for Php 7.4 redirect?
What is the right htaccess code for Php 7.4 redirect?

Time:10-05

Can someone please help me redirect the php pages to html (only in the root directory, without subfolders)? I tried dozens of solutions, but I didn't succeed. The code below redirects everywhere (including in subfolders...) I don't want the subdirectories to be affected. My domain: https://www.example.com/ Thanks in advance!

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) https://www.example.com/$1 [R=301,L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(. ?)\.php$ /$1.html [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(. ?)\.html$ /$1.php [L]
</IfModule>


<FilesMatch ".(ico|css|flv|js|gif|jpeg|png|woff|woff2|eot|svg|ttf|webp)$">
    Header set Cache-Control "max-age=604800, public, no-cache"
</FilesMatch>

CodePudding user response:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

CodePudding user response:

Have it like this:

RewriteEngine On

# add www.
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# external redirect to .html from .php request
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([^./] ?)\.php$ /$1.html [R=301,L,NC,NE]

# internal rewrite to .php from .html if corresponding php exists
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(. ?)\.html$ $1.php [L,NC]

<FilesMatch ".(ico|css|flv|js|gif|jpeg|png|woff|woff2|eot|svg|ttf|webp)$">
    Header set Cache-Control "max-age=604800, public, no-cache"
</FilesMatch>

Note that [^./] will match any character that is not a dot and not a / thus matching only in root directory skipping all sub directories.

  • Related