为了账号安全,请及时绑定邮箱和手机立即绑定

无法在 .htaccess 中正确重写和重定向 url

无法在 .htaccess 中正确重写和重定向 url

PHP
胡说叔叔 2022-01-08 20:16:24
我正在尝试使我的网站中的 url 对用户友好,但似乎服务器根本没有考虑 .htaccess 重写命令。该项目位于 中,localhost并命名为ecommerce. 我想“转换”这个 url:localhost/ecommerce/product?name=abc 到localhost/ecommerce/product/abc.这是 .htaccess 文件:RewriteEngine OnRewriteBase /## hide .php extension# To externally redirect /dir/foo.php to /dir/fooRewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]RewriteRule ^ %1 [R,L,NC]## To internally redirect /dir/foo to /dir/foo.phpRewriteCond %{REQUEST_FILENAME}.php -fRewriteRule ^ %{REQUEST_URI}.php [L]##hide /indexRewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\index [NC]RewriteRule ^ %1 [R,L,NC]##HERE IS THE IMPORTANT PARTRewriteCond %{THE_REQUEST} ^(GET|POST|HEAD)\ /product\.php\?name=([^&]+)RewriteRule ^ /product/%2/? [L,R=301]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^/?product/([^/]+)/?$ /product.php?name=$1 [L]当我访问localhost/ecommerce/product?name=abcurl 时保持原样,当我访问时localhost/ecommerce/product/abc我得到500 Internal Server Error.我以为xampp httpd.conf有问题,所以改了<Directory />    AllowOverride None    Order allow,deny    Allow from all</Directory>到<Directory />    AllowOverride All    Order allow,deny    Allow from all</Directory>它仍然不起作用!从 .htaccess 中删除我隐藏 .php 扩展名的部分也没有任何区别。
查看完整描述

1 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

用这个里面替换你的代码/ecommerce/.htaccess:


Options -MultiViews

RewriteEngine On

RewriteBase /ecommerce/


##HERE IS THE IMPORTANT PART

RewriteCond %{THE_REQUEST} /product\.php\?name=([^&\s]+) [NC]

RewriteRule ^ product/%1/? [L,R=301]


## hide .php extension

# To externally redirect /dir/foo.php to /dir/foo

RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index|(\S+?))\.php[/\s?] [NC]

RewriteRule ^ /%1%2 [R=301,L,NE]


RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^/?product/([^/]+)/?$ product.php?name=$1 [L,NC,QSA]


## To internally redirect /dir/foo to /dir/foo.php

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME}.php -f

RewriteRule ^(.+?)/?$ $1.php [L]

确保在新浏览器中测试它以避免旧浏览器缓存。


查看完整回答
反对 回复 2022-01-08
  • 1 回答
  • 0 关注
  • 150 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信