无法正确重写和重定向.htaccess中的网址

时间:2019-09-13 11:36:38

标签: php .htaccess url mod-rewrite xampp

我正在尝试使我的网站中的url用户友好,但是服务器似乎根本没有考虑.htaccess重写命令。

该项目位于localhost中,它的名称为ecommerce。 我要“转换”此URL:localhost/ecommerce/product?name=abclocalhost/ecommerce/product/abc

这是.htaccess文件:

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_URI}.php [L]

##hide /index
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\index [NC]
RewriteRule ^ %1 [R,L,NC]


##HERE IS THE IMPORTANT PART
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD)\ /product\.php\?name=([^&]+)
RewriteRule ^ /product/%2/? [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?product/([^/]+)/?$ /product.php?name=$1 [L]

当我访问localhost/ecommerce/product?name=abc时,URL保持不变,而当我访问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 个答案:

答案 0 :(得分:2)

/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]

请确保在新的浏览器中对其进行测试,以避免旧的浏览器缓存。