Apache mod_rewrite complex URL regex

偶尔善良 提交于 2019-12-12 03:13:44

问题


i want to make a beautiful URL from a URL like this:

http://example1.com/cimage/webroot/img.php?src=http://example.com/img1.jpg&w=600&h=800&q=60&sharpen&crop-to-fit

So the result URL must be somthing like this:

http://example1.com/cimage/webroot/img.php/http://example2.com/img1.jpg/600*800/60/sharpen/crop-to-fit

Now my problem create a regex for use in apache mod_rewrite. help me please. thanks...


回答1:


Based on the discussion in the comments, this is the solution:

RewriteRule ^img.php/(https?):/+(.+?(?:\.jpg|\.png))/(\d+)/(\d+)/(\d+)/?([^\/]*)/?([^\/]*)/?‌​([^\/]*)$ img.php?src=$1://$2&w=$3&h=$4&q=$5&$6&$7&$8

Demo

The logic here is to match img.php/ at the start of the string, then either http or https, :, one or more /s, the host and file name, then the various parameters for size, quality, etc.

Another way to handle this without the complicated regex is to do a simple catch-all rule like this:

RewriteRule ^img.php\/(.+) img.php?url=$1

Then you can do the parsing in PHP, mostly using simpler operations like explode() in the PHP code. This approach makes sense especially if there might be additional operations/parameters; otherwise, your regex starts to have a lot of capturing groups, making it hard to read and maintain.



来源:https://stackoverflow.com/questions/28038590/apache-mod-rewrite-complex-url-regex

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