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

rewrite and force redirect on rewrite origin url in nginx

· 52CE 我爱测

I have this instance where a html search <form> forces it to go to /search/index.php?q=term and would like to use something like /search/term instead. This is how the config looks like right now: location /search/ { rewrite ^/sea…

问题原文

原帖链接 · Typewar · CC BY-SA 4.0

I have this instance where a html search <form> forces it to go to /search/index.php?q=term and would like to use something like /search/term instead.

This is how the config looks like right now:

location /search/ {
    rewrite ^/search/(.+) /search/index.php?q=$1;
}

Accessing this location directly works, but in the moment of filling out the form, and searching it will use the "origin" rather than the rewrite.

I tried using redirect "backwards", but that crashed the nginx service:

location /search/ {
    rewrite ^/search/(.+) /search/index.php?q=$1;
    redirect ^/search/index.php?q=(.+) /search/$1;
}

I also tried rewrite with permanent flag, which didn't do anything

location /search/ {
    rewrite ^/search/(.+) /search/index.php?q=$1;
    rewrite ^/search/index.php?q=(.+) /search/$1 permanent;
}

I know it's possible to achieve the same thing in PHP with something like this:

// On the top of /search/index.php
if (str_starts_with($_SERVER['REQUEST_URI'], '/search/index.php')){
    $protocol = ($_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") ? "https" : "http";
    $server = $_SERVER['HTTP_HOST'];
    $queries = array();
    parse_str($_SERVER['QUERY_STRING'], $queries);
    $search = $queries['q'] ?? "";
    header("Location: $protocol://$server/search/$search");
}

But think it would be better if nginx could handle this (if it's possible at all).

Does anyone know how to rewrite, and redirect access from the origin ?

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

The existing configuration is something like:

location /search/ {
    rewrite ^/search/(.+) /search/index.php?q=$1;
}
location ~ \.php$ {
    ...
}

The URI /search/index.php is used internally, so attempting to use rewrite ^/search/index.php?q=(.+) /search/$1 permanent; will generate a redirection loop.

To identify the URI as an external request, you need to look at the $request_uri variable. And for that, you will need to use the infamous if statement. For example:

if ($request_uri ~ ^/search/index\.php\?q=(.+)) {
    return 301 /search/$1;
}
location /search/ {
    rewrite ^/search/(.+) /search/index.php?q=$1;
}
location ~ \.php$ {
    ...
}

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

资料来源与适用范围

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

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

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