.htaccess rewrite url does not work

2019-09-10 02:58发布

I would like to rewrite the following URL:

http://www.domain.com/cars/cars.php?cars_item=231

To

http://www.domain.com/cars/231/

I have tried the following coding but cannot get it working for some reason.

In sub-folder cars I placed the .htaccess file which includes:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteRule ^([0-9]+)\/?$ cars.php?cars_item=$1 [NC]
</IfModule>

Apache is configured properly as I have tried a redirect from one domain to another using an .htaccess file and works fine.

Could someone please explain to me what I'm doing wrong?

标签: .htaccess
1条回答
【Aperson】
2楼-- · 2019-09-10 03:42

This rule should do what you want:

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

# Redirect cars.php?cars_item=231 to cars/231/
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+cars/cars\.php\?cars_item=([^&\s]+) [NC]
RewriteRule ^ /cars/%1? [R=302,L]

# Internally forward cars/231/ to cars.php?cars_item=231
RewriteRule ^cars/([0-9]+)/?$ /cars/cars.php?cars_item=$1 [NC,L]

The first rule is in charge of receiving the unfriendly URL and converting it to a friendly URL.

The second rule will redirect it internally not changing the browser URL.

These rules should be placed on the root of your domain in your case the folder before cars.

You need to do it like this in order to avoid a redirect loop unless you're using a newer version of HTTPD but since I do not know any server specifics I just gave you a generic example.


If all you want is to be able to access:

http://www.domain.com/cars/231/

Without redirecting the original URL then you could just use:

RewriteRule ^cars/([0-9]+)/?$ cars/cars.php?cars_item=$1 [NC,L]

The above rule takes care of receiving the above mentioned URL and send it to the proper handler.

查看更多
登录 后发表回答