Remove .html and .php extensions with .htaccess

前端 未结 2 1965
情书的邮戳
情书的邮戳 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条回答
  •  情话喂你
    2020-11-30 08:58

    Yes, I know that this question was asked multiple times already and is answered, but I will give a little more comprehensive answer based on my experience.

    Here is the .htaccess code snippet that will help you:

    # Apache Rewrite Rules
     
      Options +FollowSymLinks
      RewriteEngine On
      RewriteBase /
    
    # Add trailing slash to url
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
      RewriteRule ^(.*)$ $1/ [R=301,L]
    
    # Remove .php-extension from url
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_FILENAME}\.php -f
      RewriteRule ^([^\.]+)/$ $1.php 
    
    # End of Apache Rewrite Rules
     
    

    I want to stress some important things here for everybody's reference:

    • This code snippet doesn't remove entry scripts from url (such as index.php used by many PHP frameworks)
    • It only removes .php extension, if you want to remove other extension as well (e.g. .html), copy and paste 3rd block and replace php with other extension.
    • Don't forget to also remove extension from anchors (links) href.

提交回复
热议问题