skip to Main Content

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>

2

Answers


  1. 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]
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search