mod_rewrite to text/type/id

偶尔善良 提交于 2019-12-19 04:09:01

问题


My current code is something like this

store.php?storeid=12&page=3

and I'm looking to translate it to something like this

mysite.com/roberts-clothing-store/store/12/3

and something like this:

profile.php?userid=19

to

mysite.com/robert-ashcroft/user/19

I understand that it's best to have the SEO-friendly text as far left as possible, ie not

mysite.com/user/19/robert-ashcroft

(what stackoverflow does)

I can't figure out how to do this in apache's mod_rewrite.


回答1:


Actually, you may have to think "upside-down" with mod_rewrite.

The easiest way is that to make your PHP emit the rewritten mysite.com/roberts-clothing-store/store/12/3 links.

mod_rewrite will then proxy the request to one PHP page for rewrite.php?path=roberts-clothing-store/store/12/3 that will decode the URL and sets the arguments (here storeid and page) and dynamically include the correct PHP file, or just emit 301 for renamed pages.

A pure solution with mod_rewrite is possible, but this one is much easier to get right, especially when you don't master mod_rewrite.

The main prob could be with the overhead that might be significant but is the price of simplicity & flexibility. mod_rewrite is much faster

Update:

The other posts do answer the question, but they don't solve the typical duplicate-content problem that avoided by having canonical urls (and using 301/404 for all those URLs that seems ok, but aren't).




回答2:


Try these rules:

RewriteRule ^[^/]+/store/([0-9]+)/([0-9]+)$ store.php?storeid=$1&page=$2 
RewriteRule ^[^/]+/user/([0-9]+)/ profile.php?userid=$1

But I wouldn’t use such URLs. They don’t make sense when you think of the URL path as a hierarchy and the path segments as their levels.




回答3:


RewriteRule ^roberts-clothing-store/store/([^.]+)/([^.]+)$ store.php?id=$1&page=$2
RewriteRule ^robert-ashcroft/user/([^.]+)$ profile.php?userid=$1



回答4:


Then you can just use RewriteRule directive in a .htaccess like:

RewriteRule roberts-clothing-store/store/(\d+)/(\d+)$ store.php?storeid=$1&page=$2 [L]

See http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html for help, or google.




回答5:


My approach is to make the .htaccess as easy as possible and to do all the hard work in PHP:

RewriteRule ^(.*?)$ index.php?$1

This basically means to take everything and reroute it to my index.php file (in css/javascript/image directories I simply use "RewriteEngine off" to grand access to these files). In PHP I than just split("/", $param, 5) the string and run a foreach() to check all the parameters. Encapsulated in a nice function this works fine for me.

Update:

For this easy case I highly recommend the use of explode() instead of using split(), because explode() doesn't come with the overhead by using regular expressions.



来源:https://stackoverflow.com/questions/1024151/mod-rewrite-to-text-type-id

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