Mod_rewrite

My current code is something like this

store.php?storeid=12&page=3 

and I want 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 is best to have the most convenient SEO text, i.e. not

 mysite.com/user/19/robert-ashcroft 

(what stackoverflow does)

I cannot figure out how to do this in apache mod_rewrite. Any help?

+4
source share
5 answers

In fact, you might have to think upside down with mod_rewrite .

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

mod_rewrite will proxy a single-page PHP request for rewrite.php?path=roberts-clothing-store/store/12/3 , which will decode the strong> URL and storeid arguments (here storeid and page ) and dynamically include the correct PHP file , or only for 301 for renamed pages.

A clean solution with mod_rewrite possible, but it is much easier to get right, especially if you do not master mod_rewrite .

the main problem may be with service data , which can be significant, but this is the price of simplicity and flexibility. mod_rewrite much faster

Update:

Other do posts answer the question, but they do not solve the typical duplicate content issue, which is avoided by canonical URLs (and using 301/404 for all of these URLs that look fine but not).

+4
source

Try the following rules:

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

But I would not use such URLs. They do not make sense when you consider a URL path as a hierarchy and path segments as your levels.

+2
source

Then you can simply use the RewriteRule directive in .htacces, for example:

 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.

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

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

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

This basically means taking everything and redirecting it to the index.php file (in the css / javascript / image directories, I just use "RewriteEngine off" to access these files). In PHP, I just split the ("/", $ param, 5) line and ran foreach () to check all the options. Encapsulated in a nice feature, this works great for me.

Update:

In this simple case, I highly recommend using explode () instead of using split (), because explode () does not come with overhead using regular expressions.

+1
source

Source: https://habr.com/ru/post/1286539/


All Articles