Little mod_rewrite problem

这一生的挚爱 提交于 2020-01-04 18:57:32

问题


I have a classifieds website. Each classified is linked like this originally:

   mydomain.com/ad.php?ad_id=Bmw_M3_M_tech_113620829

What RewriteRule should I use to make this link look like:

   mydomain.com/Bmw_M3_M_tech_113620829

Also, what do I need to add to my .htaccess file? This is what I have so far:

Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteBase /

And I have just enabled mod_rewrite which was disabled at first on my Ubuntu server by using:

 a2enmod rewrite

Anything else I need to know or do?

Thanks


回答1:


It looks like you need something like this:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/ad\.php
RewriteRule ^(.*)$ ad.php?ad_id=$1 [L]

This should rewrite a request to mydomain.com/Bmw_M3 into mydomain.com/ad.php?ad_id=Bmw_M3.

The RewriteCond excludes direct requests to ad.php from being rewritten. The RewriteRule would simply substitutes anything after mydomain.com/ in place of the $1. The [L] (last) flag stops the rewriting process so that it won't apply any more rewrites for a request that is rewritten by this rule.




回答2:


You need to add the rule itself. Requires regex =)

RewriteRule ([a-zA-Z0-9_]+) ad.php?ad_id=$1

Of course, this regex should be fine tuned based on the ad ID you're passing on - by telling what characters can be in that ad ID and similar. For example, if all ad IDs are ending with and underscore and 9 digits, something like this:

RewriteRule ([a-zA-Z0-9_]_[0-9]{9}) ad.php?ad_id=$1

Oh, also, after enabling mod_rewrite restart apache. Make sure that AllowOverride is not set to None, cause in that case, apache will ignore .htaccess files in directories.



来源:https://stackoverflow.com/questions/2991396/little-mod-rewrite-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!