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

Nginx - populate REQUEST_URI with rewritten URL

· 52CE 我爱测

I have an Nginx configuration that is for a new PHP application that has the same functionality as another legacy PHP application, but different URLs. I want to preserve the paths of the old application, replacing the /foo path p…

问题原文

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

I have an Nginx configuration that is for a new PHP application that has the same functionality as another legacy PHP application, but different URLs.

I want to preserve the paths of the old application, replacing the /foo path prefix with /page and replacing the special path /foo/bar with /page/otherBar :

    # legacy support
    location ~ ^/foo/bar {
        rewrite /foo/bar /page/otherBar$1 last;
    }

    # How to rewrite all other pages starting with "/foo" ?

    # END legacy support

    location / {
        # try to serve file directly, fallback to front controller
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        proxy_read_timeout 300;
        include        fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_param  SCRIPT_FILENAME /usr/share/nginx/www/$fastcgi_script_name;
        fastcgi_param  PATH_INFO       $fastcgi_path_info;
        fastcgi_param  PATH_TRANSLATED $document_root$fastcgi_script_name;
        fastcgi_pass   unix:/var/run/php/php7.0-fpm.sock;
    }

This approach does not work, because $request_uri, which gets passed to REQUEST_URI in the fastcgi_params include file, still contains /foo/bar.

I've tried setting REQUEST_URI to $fastcgi_path_info but that fails for all non-rewritten URLs as it is empty then. $uri also does not work because it just contains /index.php?

Is there any variable for the third location config that contains the rewritten path?

已采纳解答

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

$request_uri has the value of the original URI and $uri has the value of the final URI. You could use the set directive to save a snapshot of $uri from inside the location / block and use it later to generate the REQUEST_URI parameter.

Like this:

location / {
    set $save_uri $uri;
    try_files $uri /index.php$is_args$args;
}

location ~ ^/index\.php(/|$) {
    include  fastcgi_params;
    fastcgi_param  REQUEST_URI $save_uri;
    ...
}

See this document for more.

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

资料来源与适用范围

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

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

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