问题
I'm trying to come up with one or more rewrite rules that will take either a friendly url or a url containing the full query string.
The plan is to create a text-only page by reading in the URL using PHP's loadHTML.
For example:
Input
1. http://www.example.com/disclaimer (http://www.example.com/text/disclaimer on text-only version)
2. http://www.example.com/info/aboutus (http://www.example.com/text/info/aboutus on text-only version)
3. http://www.example.com/news?id=123 (http://www.example.com/text/news?id=123 on text-only version)
Output
1. http://www.example.com/includes/textonly.php?page=disclaimer
2. http://www.example.com/includes/textonly.php?page=info/aboutus
3. http://www.example.com/includes/textonly.php?news?id=123
So on the textonly.php I would use $_GET['page']); for example 1) and 2), and use $_SERVER['QUERY_STRING']; for example 3).
For example 1) and 2), I came up with:
RewriteRule ^text/(.*) includes/textonly.php?page=$1
And for example 3), I came up with:
RewriteRule ^text/(.[?]) /includes/textonly.php [QSA]
They work independantly but not together. Can anyone help?
回答1:
With guidance from Tom and Michael, this is what I've come up with:
in Htaccess send everything to PHP in the querystring:
RewriteRule ^text/(.*) /includes/textonly.php [QSA,L]
Then in PHP:
$page = 'http://'.$_SERVER['HTTP_HOST'].'/'.str_replace('/text/','',$_SERVER['REQUEST_URI']);
Seems to work for both friendly urls (2 levels deep tested so far) and querystrings. Hopefully its okay, so I'll go with this as a solution :)
回答2:
I suggest handing control over to PHP - I wrote an article on this a while ago - http://tomsbigbox.com/elegant-url-rewriting/ - it details how to send the query string to a PHP file that then decides what to do - so if the page exists for example it will load it, otherwise do something else.
I've found that to be the best solution to URL rewriting.
回答3:
I'd change your rewrite rule to look like this:
RewriteRule ^([^/\.]+)/?([^/\.]+)?/?$ /includes/textonly.php?page=$1&id=$2 [L,NC]
Then slightly modify your Input URLs to look like this:
1. http://www.example.com/disclaimer
2. http://www.example.com/info/aboutus
3. http://www.example.com/news/123
And they would point to these URLs:
1. http://www.example.com/includes/textonly.php?page=disclaimer&id=
2. http://www.example.com/includes/textonly.php?page=info&id=aboutus
3. http://www.example.com/includes/textonly.php?page=news&id=123
The regex above will match anything between the /
, not including a /
or a .
. The second half is optional, so in that rule, you could only go two directories deep.
Controlling all three URLs in the same way will make your logic a little cleaner on the textonly.php
page as you do not need to write special logic for the first two URLs compared to the last.
来源:https://stackoverflow.com/questions/6468766/htaccess-rewrite-to-capture-friendly-url-or-querystring