How can I make all my urls extensionless, without

2019-02-24 23:46发布

问题:

I want to make all my URLs uniformly clean. Which means all my URLs have no extensions, nor trailing slash, and if a person does enter in a .php or trailing slash, it would simply redirect the person to the clean URL.

Example:

example.com/blog/file.php

and

example.com/blog/file/

would both redirect to

example.com/blog/file

回答1:

In .htaccess try this:

RewriteEngine on

#unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

#resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

#redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php /$1 [R=301,L]


回答2:

My web host recently (Sept 2011) updated their Apache servers to a newer version of Apache, and my old .htaccess code to display extensionless URLs no longer worked. After a considerable amount of copying code (that probably worked with older versions of the Apache OS) and unsuccessfully testing, I was able to determine that the following code seems to work on my server, and several others:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

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

RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php http://www.example.com/$1 [R=301,L]

Give that a try - the -Multiviews seemed to be the key element to get it to work.



回答3:

If you're website is hosted on a Linux server with the Apache Mod-Rewrite moduled enabled, you can use .htaccess to redirect your files. This linkwith information on how to format the file for your purpose may help.



回答4:

# Turn off the need of directory slash redirecting
DirectorySlash Off

# Turn on RewriteEngine
RewriteEngine On

# Internally redirect request to php file
RewriteCond "%{REQUEST_FILENAME}" !-f
RewriteCond "%{REQUEST_FILENAME}\.php" -f
RewriteRule "(.*)" "$1.php" [L]

# External redirects
# The above line is used to determine whether a internal redirect is done or not.
# If it is internally redirected, REDIRECT_STATUS will become 200.
# RewriteCond "%{ENV:REDIRECT_STATUS}" "^$"

# Redirect request with .php extension to extensionless
RewriteCond "%{ENV:REDIRECT_STATUS}" "^$"
RewriteRule "(.*)\.php$" "$1" [R=301]

# Redirect request with trailing slash to slashless
RewriteCond "%{ENV:REDIRECT_STATUS}" "^$"
RewriteCond "%{REQUSET_FILENAME} -d
RewriteCond "%{REQUSET_FILENAME} !-f
RewriteRule "(.*)\/" "$1" [R=301]