Is it possible to use mod_rewrite htaccess to rewr

2019-05-15 04:11发布

问题:

If I have a URLhttp://www.domain.com/listing.php?company_id=1 is it possible for me to re-write that to http://www.domain.com/company-name by using that id to pull the name from the database.

Or do I have to change listing.php to make it ?company_name=company-name

If anyone can point me in the right direction that would be great.

Thanks!

回答1:

A map function allows using no id in the url at all, while still using the id in the rewritten url to do the database lookup.

http://www.domain.com/another-one

maps to

http://www.domain.com/listing.php?company_id=3423

Here is how I use map text files, which I generate from a database query. I believe mod_rewrite also does mapping to a database directly, of which I'm unfamiliar (maybe someone can provide that answer). I use Helicon Tech's isapi_rewrite v3, which works like mod_rewrite, so this should work for you.

Sample map file named map_company.txt

some-company 12
another-one 3423
freds-fill-dirt-and-croissants 44

The rewrite rules:

RewriteMap map_company txt:map_company.txt [NC] 

RewriteCond ${map_company:$1|NOT_FOUND} !NOT_FOUND
RewriteRule ^/(.*) /listing.php?company_id=${map_company:$1} [NC,QSA,L]

RewriteMap assigns the map_company.txt text file to a variable named map_company (named the same just to be consistent).

RewriteRule is doing the work. It captures everything after the slash into $1, then rewrites it to your listing.php url. The ${map_company:$1} is looking up the url in the map file, and returning the id.

RewriteCond is just doing a double-check to see if the listing is there. The $1 is coming from the RewriteRule url, the NOT_FOUND is a default value if not found, and the condition is if it's not-NOT_FOUND (a little tangled - but it's just checking if it's in the file). If it's in the file, the RewriteRule will be run. If it's not in the file, it skips the RewriteRule, and falls through to more rules (perhaps to a page-not-found or some other default).



回答2:

You'll need the id in both the urls, but only use the full name in the pretty link for the user. The following would rewrite http://www.domain.com/42/company_name to http://www.domain.com/listing.php?company_id=42 and just discard the company name.

RewriteEngine on
RewriteRule ^([0-9]*)/([A-Za-z0-9_]*)/$ /listing.php?company_id=$1 [L]

Note that a user could also visit http://www.domain.com/42/wrong_name and still land on the right page with the right company name. If this isn't desired you could change the rule to /listing.php?company_id=$1&company_name=$2 and check for equality in listings.php