大网数据广告活动
服务器运维问答

nginx extracting from request_uri and adding it to redirct destination

· 52CE 我爱测

i am currently moving new builds of an existing site onto a new server using nginx and have been told the URL need to direct to a new PHP file to handle how to pick out the date from a new DB. an example incoming URL would be : h…

问题原文

原帖链接 · Jimjebus · CC BY-SA 3.0

i am currently moving new builds of an existing site onto a new server using nginx and have been told the URL need to direct to a new PHP file to handle how to pick out the date from a new DB.

an example incoming URL would be :

https://testsite.com/test-account-here-ABC-123456.html

This is to be caught by nginx and redirected to

https://testsite.com/profiles.php

where the file will do its bit and extract the url to get its details and do its search.

I've set up a redirect on the premise the $request_uri finds **-ABC-* within the url like so :

if ($request_uri ~ ^/(.*)-ABC-)
{
    return 302 $scheme://testsite.com/profile.php;
}

which successfully goes to that PHP file but i need to be able to extract the numbers from the URL (123456) so i can access them via query string in the PHP file, i've tried to user

return 302 $scheme://testsite.com/profile.php?url=$request_uri;

but that returns the full url which causes a infinite redirect loop and the browser to error.

Is there anyway you can extract parts of a $request_uri to then re-use in the redirect?

Something along the lines of

return 302 $scheme://testsite.com/profile.php?url=$variable1;

已采纳解答

原帖链接 · Tero Kilkanen · CC BY-SA 3.0

If the numbers are always before the .html suffix, you can use this configuration:

location ~ ^/.+-ABC-([0-9]+)\.html$ {
    return 302 $scheme://testsite.com/profile.php?url=$1;
}

Using location is the preferred way of doing these kind of things in nginx. The ~ tells nginx to use regular expression matching to find the location. The string after that and before { is the actual regular expression string.

Here we match any string which has any characters at start, followed by -ABC- and then any numbers, and then ending with .html suffix.

The numbers are captured into a variable $1, because the regular expression for that part is inside parentheses.

If you want to further elaborate on the regular expression, there are plenty of regular expression tools online where you can test your modifications.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-07-11)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。