Using .htaccess to remove PHP file extension from

2020-04-07 06:40发布

问题:

I just finished installing a LAMP stack on Ubuntu 12, and have run into an issue with Apache's .htaccess file. I have the rewrite and redirect mods enabled, and the .htaccess file is working (the URI will redirect to 'www' if there is no 'www' present), but no matter what I try, I cannot get it to remove file extensions. I've tried the <Files> directive with no luck. My current file consists of the following:

RewriteEngine On

# Remove file extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*)$ $1.php [L]

# Force www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Any suggestions on how to fix this very annoying problem?

回答1:

You don't use htaccess to do this, you use your app to remove the extensions, and htaccess to map extension-less urls to real files. This rule

# Remove file extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) $1.php [L]

Says, "if the requested resource doesn't exist as a file, look for the resource with a .php extension". So you remove the extension from all links in your app, and this rule will make the php file run without the extension. Your htaccess is fine as-is, you need to update your app.



回答2:

# Apache Rewrite Rules
 <IfModule mod_rewrite.c>
  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
 </IfModule>


回答3:

There is another htaccess alternative I use very successfully:

Options +FollowSymLinks

Options -Indexes

RewriteEngine On

RewriteRule ^purchase-jelly-babies$ /modules/products/jelly_babies.php [L]

RewriteRule ^/lets/use/an/asp/extension.asp$ /modules/test/asp_example.php [L]

This method not only solves your PHP extension issue but also allows you to keep your files organized no matter what those SEO idiots tell you what the URL should be.



回答4:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)/$ $1.php 


回答5:

Please try This code and tell me it performance.

  RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/$ $1.php

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)/$ $1.html

RewriteCond %{REQUEST_FILENAME}.py -f
RewriteRule ^(.*)/$ $1.py


回答6:

the way am doing it.

RewriteEngine on
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://domainname.com/$1 [R=301,L]