Change Displayed URL Structure using mod_rewrite N

2019-08-21 21:21发布

I need to change the structure of the displayed client-side URL. I'm not too skilled using regex and coding for the .htaccess file. Basically, I have a structure that looks something like:

http://www.example.com/catalog/index.php?cat=lt&sec=lt1-1&id=nmlt10.  

I would like this to be displayed in the address bar as:

http://www.example.com/catalog/lt/lt1-1/nmlt10.  

This is what I came up with, but it has had no effect:

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/([^/]*)\$ /catalog/index.php?cat=$1&sec=$2&id=$3 [L]

I tested and removed any other rules in the .htaccess file to ensure nothing was being overwritten. I'm on a shared hosting apache server, and know that mod_rewrite is enabled, because I use it to rewrite non-www to www urls. I don't receive and 500 error messages, I just do not notice any change at all. I'm not sure where I'm going wrong here, so hopefully someone can point me in the right direction.

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-21 21:51

Finally found a solution that worked:

RewriteEngine On
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php?cat=$1&sec=$2&id=$3 [QSA,L]

Appreciate LazyOne's response to get me on the right track; however, when using:

RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?cat=$1&sec=$2&id=$3 [QSA,L]

I wasn't able to following links that were already placed on the site, it treated different directories as the variables, for example, when browsing to an image or file, say:

folder/folder/image.png

It would grab "folder" - "folder" - and "image" as the variables. I can see why that was happening, if anyone has a different solution or an explanation, please let me know, I'm always willing to learn.

查看更多
姐就是有狂的资本
3楼-- · 2019-08-21 22:02

Since your .htaccess is in website root folder, then you should use thus rule:

RewriteEngine On
RewriteBase /

RewriteRule ^catalog/([^/]+)/([^/]+)/([^/]+)$ /catalog/index.php?cat=$1&sec=$2&id=$3 [QSA,L]

If you place it in .htaccess in /catalog/ folder, then you can remove catalog from it:

RewriteEngine On

RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?cat=$1&sec=$2&id=$3 [QSA,L]

I have tested rule before posting -- works fine for me.


This rule (same as above) will check if URL is a file or folder and will only rewrite if it is not:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?cat=$1&sec=$2&id=$3 [QSA,L]
查看更多
登录 后发表回答