Remove .php and .html extensions AND have directories with same name?

后端 未结 2 1988
广开言路
广开言路 2020-12-20 02:48

I want to remove the .php and .html extensions of my website pages in the browser. I found this code online to add in the .htaccess file:

RewriteEngine on
Re         


        
相关标签:
2条回答
  • 2020-12-20 02:57

    You could be able to give a priority to file when it request comes without / with same name with directory as well as removing both php & html and determine which one to check first like this :

    DirectorySlash Off
    RewriteEngine on 
    RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index)?(.*?)\.(php|html)[\s?/] [NC]
    RewriteRule ^ /%1%2 [R=302,L,NE]
    RewriteCond %{REQUEST_FILENAME}   !-f 
    RewriteCond %{REQUEST_FILENAME}\.php -f 
    RewriteRule ^(.*) /$1.php [L]
    RewriteCond %{REQUEST_FILENAME}   !-f 
    RewriteCond %{REQUEST_FILENAME}\.html -f
    RewriteRule ^(.*) /$1.html [L]
    RewriteCond %{REQUEST_FILENAME}   !-f 
    RewriteCond %{REQUEST_URI} !\/$
    RewriteRule ^(.*) %{REQUEST_URI}/ [L,R=302]
    

    So , by the code above , extensions will be removed then will check first if there is php file match this , then html and finally if there is a directory .

    So , the request for /home only will check first a php that named home if it is exist ok , then directory home but the request /home/about will go directly to about inside home directory.

    Clear browser cache then test it , if it is Ok , change 302 to 301 to get permanent redirection

    0 讨论(0)
  • 2020-12-20 03:22

    You can try with this simple code in your .htaccess

    RewriteEngine On
    RewriteRule ^([^\.]+?)/?$ $1.php [NC,L]
    

    Update: As @Niet mentioned I missed condition so add this line before rule.

    RewriteCond %{REQUEST_FILENAME}\.php -f
    
    0 讨论(0)
提交回复
热议问题