.htaccess 301 重定向 + URL 重写

.htaccess 301 Redirect + URL Rewrite

我得到了一个 .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= [QSA,L]

我想要完成的是,当有人试图访问旧的 301 重定向 url 时,url 也会被重写,所以当转到 http://example.com//someoldpage.php you see the url http://example.com/fancyurl and NOT like now: http://example.com/index.php?page=fancyurl

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= [QSA,L]

我遇到了这个问题,并在我的案例中找到了解决方案,在您的 htaccess 中使用以下代码将 url 从 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]