简体   繁体   中英

hide extension and redirect url with extension

I have this code that redirects all .php to no extension:

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

So /example.php = /example

I would like it so if someone clicks on /example.php that they would automatically end up at /example instead.

What would be the best way to go about it? Would having both links work be considered duplicate content?

Try this one:

RewriteEngine On

# if requested .php file directly, then redirect to extension-less URL
# (do it on initial rewrite iteration only)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.+)\.php$ /$1 [R=301,L]

# Your "add .php file extension" rule goes below

The problem with this approach is that %{ENV:REDIRECT_STATUS} variable may not be populated/supported by your Apache setup/configuration. Unfortunately I do not know what needs to be done to have it working.


If the above does not work, try this workaround -- it will work but not that "nice" and may fail under some circumstances (query string value is the weak point here):

RewriteEngine On

# if requested .php file directly, then redirect to extension-less URL
# (do it on initial rewrite iteration only)
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+
RewriteRule ^(.+)\.php$ /$1 [R=301,L]

# Your "add .php file extension" rule goes below

Rewrite condition in this rule is important -- without it you will have endless redirect loop, which your browser will abort at some point (unless it is not smart enough (or request is done by some poorly coded bot) and such process has to be killed manually).

It does not really matter if you place such redirect rule above or below your "add .php file extension" rule -- I just prefer keeping all 301 Redirects close to the top.

You can do a 301 "moved permanently" redirection, which informs the client that the requested resource has moved and is available at a new location. To do that using RewriteRule , add a [R=301,L] flag to the rule specification, eg:

RewriteRule ^(.*)/$ $1.php [R=301,L]

This is considered the "search engine friendly" redirection method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM