.htaccess 301重定向+ URL重写

时间:2015-01-07 04:05:25

标签: .htaccess redirect url-rewriting

我有一个非常接近的.htaccess:

# disable directory browsing
Options All -Indexes

# start rewrites
RewriteEngine on

Redirect 301 /someoldpage.php http://example.com/fancyurl

# if not a file, and not a directory, reroute through index as normal page
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

我想要实现的是,当有人试图访问旧的301重定向网址时,网址也会被重写,因此当转到http://example.com//someoldpage.php时,您会看到网址http://example.com/fancyurl而不是现在: http://example.com/index.php?page=fancyurl

2 个答案:

答案 0 :(得分:0)

Redirect是mod_alias的一部分,而重写的东西是mod_rewrite的一部分。这两个不同的模块都应用于同一个请求,从而导致它同时重定向和重写。如果请求为/someoldpage.pjp重写为index.php,您要做的是重定向,因此您只需要在此处使用mod_rewrite:

# disable directory browsing
Options All -Indexes

# start rewrites
RewriteEngine on

RewriteRule ^someoldpage\.php$ http://example.com/fancyurl [L,R=301]

# if not a file, and not a directory, reroute through index as normal page
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

答案 1 :(得分:0)

我解决了这个问题,并在我的案例中得到了一个解决方案,使用htaccess中的以下代码将example.com/about.php的网址重写为example.com/about

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_FILENAME}.php [L]