简体   繁体   中英

In Apache, how do I redirect from a specific path and query string?

I want to redirect from, eg,

http://mystore.com/category.php?id=123

to

http://mystore.com/categories/foo

and also from, eg,

http://mystore.com/product.php?id=456

to

http://mystore.com/products/bar

These will be permanent (301) redirects and there will be about a dozen of them. I don't need to extract any information from the paths or query strings, I just need to match them exactly. And I would like avoid specifying absolute URLs if at all possible.

I figure this can be done with mod_rewrite and some combination of RewriteCond s and RewriteRule s, but I'm already doing some URL rewriting and my attempts so far have had undesired results.

Here's an anonymised excerpt from my .htaccess file before any modifications:

RewriteBase /

RewriteRule sitemap.xml index.php?route=sitemap [L]

# skip files and directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([^?]*) index.php?route=$1 [L,QSA]

This works as intended. I've tried adding several different combinations of conditions and rules just before the last line, most recently

RewriteCond %{QUERY_STRING} id=123
RewriteRule category.php categories/foo [L,R=301]

Something about that last rule causes problems. The home page loads, but style sheets, images, and other resources do not.

At this point, I'm considering just creating PHP scripts named category.php and product.php to handle the redirects.... Am I just a few characters away from the solution?

The resources (styles sheets, images etc.) are not loaded because there might be relative paths which have become invalid.

The problem is that the browser considers "categories" to be a folder and so the path to the resources is not valid.

A quick fix (if you are running on a domain/subdomain and not in a folder) is to put / in the path of all your resources.

For example: change style.css to /style.css so it is still included when you are on the categories page.

I never did figure out the problem, but I solved it by changing the order of the directives and nothing else. I moved the new redirects to just after the RewriteBase directive and everything works perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM