Remove .html and .php extensions with .htaccess

前端 未结 2 1962
情书的邮戳
情书的邮戳 2020-11-30 08:14

How do I remove the file type from my webpages without creating a new directory and naming the file index.php. I want http://example.com/google.html to http://example.com/go

2条回答
  •  Happy的楠姐
    2020-11-30 08:58

    @armanP's accepted answer above does not remove .php extension from php urls. It just makes it possible to access php files without using .php at the end. For example /file.php can be accessed using /file or /file.php but this way you have 2 diffrent urls pointing to the same location.

    If you want to remove .php completely, you can use the following rules in /.htaccess :

    RewriteEngine on 
    #redirect /file.php to /file
    RewriteCond %{THE_REQUEST} \s/([^.]+)\.php [NC]
    RewriteRule ^ /%1 [NE,L,R]
    # now we will internally map /file to /file.php
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.*)/?$ /$1.php  [L]
    

    To remove .html ,use this

     RewriteEngine on
     #redirect /file.html to /file
     RewriteCond %{THE_REQUEST} \s/([^.]+)\.html [NC]
     RewriteRule ^ /%1 [NE,L,R]
     # now we will internally map /file to/ file.html
     RewriteCond %{REQUEST_FILENAME}.html -f
     RewriteRule ^(.*)/?$ /$1.html  [L]
    

    Solution for Apache 2.4* users :

    If your apache version is 2.4 ,you can use the Code without RewriteConditions On Apache 2.4 we can use END flag instead of the RewriteCond to prevent Infinite loop error.

    Here is a solution for Apache 2.4 users

     RewriteEngine on
    
     #redirect  /file.php to /file
      RewriteRule ^(.+).php$ /$1 [L,R]
     # now we will internally map /file to /file.php
     RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.*)/?$ /$1.php [END]
    

    Note : If your external stylesheet or images aren't loading after adding these rules ,to fix this you can either make your links absolute changing .Notice the / before the filename . or change the URI base add the following to head section of your Web page .

    Your Webpage fails to load css and js due to the following reason :

    When your browser url changes from /file.php to /file server thinks that /file is a directory and it tries to append that in front of all relative paths . For example : when your url is http://example.com/file/ your relative path changes to thus the image fails to load . You can use one of the solutions I mentioned in the last peragraph to solve this issue.

提交回复
热议问题