你如何使用Nginx重写模块来改变请求的URI


How do you use the Nginx rewrite module to change the request URI?

我想使用一个PHP文件,它使用请求的URI来决定显示什么内容,同时确保URL是用户友好的。前者很容易实现,然而,当我试图实现后者时,我遇到了麻烦。

我相信这正是Nginx重写模块所做的那种事情,但我在理解文档方面遇到了麻烦,我无法让它以我期望的方式工作。因此,在这一点上,我质疑我对模块的理解是否正确。

这是我想要达到的,最简单的:

  1. 用户转到http://www.example.com/another-page。这是用户看到的唯一URL,它非常漂亮和整洁。
  2. Nginx将此理解为http://www.example.com/index.php?page=another-page并将请求传递给index.php
  3. index.php使用查询的参数来决定显示什么内容。
  4. Nginx以index.php的输出响应用户。

我是这样做的:

Nginx.conf

server {
    listen                        80;
    listen                        [::]:80;
    server_name                   localhost;
    try_files                     $uri $uri/ =404;
    root                          /path/to/root;
    # Rewrite the URL so that is can be processed by index.php
    rewrite ^/(.*)$ /index.php?page=$1? break;
    # For processesing PHP scripts and serving their output
    location ~* '.php$ {
        fastcgi_pass    unix:/var/run/php5-fpm.sock;
        fastcgi_split_path_info ^(.+'.php)(/.+)$;
        try_files $fastcgi_script_name =404;
        set $path_info $fastcgi_path_info;
        fastcgi_param PATH_INFO $path_info;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
    # For serving static files
    location ^~ /static/ {
    root            /path/to/static;
    }
}

index . php

$uri = $_SERVER['REQUEST_URI'];
switch ($uri){
    case '/index.php?page=':
    echo 'Welcome home';
    break;
    case '/index.php?page=another-page':
    echo 'Welcome to another page';
    break;
}
return;

我哪里出错了?

我已经尝试使用这个重写规则和var_dump($_SERVER['REQUEST_URI'])的多个版本来查看规则如何影响URI,但它从来没有像我想要或期望的那样。我曾尝试将规则置于~* '.php$位置上下文中,对正则表达式进行轻微更改,从上下文中删除和添加try_files等。我总是先用regexpal检查我的正则表达式,然后重新加载Nginx配置文件。在任何情况下,我要么得到一个500错误,要么URI保持不变。

你想要实现的是可以通过以下配置:

server {
    listen           80;
    listen           [::]:80;
    server_name      localhost;
    root             /path/to/root;
    index            index.php;
    location / {
        try_files    $uri    $uri/    /index.php?$args;
    }
    # For processesing PHP scripts and serving their output
    location ~* '.php$ {
        fastcgi_pass  unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi.conf;
    }
    # For serving static files
    location ^~ /static/ {
        root            /path/to/static;
    }
}

和稍微不同的index.php:

$uri = strtok($_SERVER['REQUEST_URI'], '?');  //trim GET parameters
switch ($uri){
    case '/':
    echo 'Welcome home';
    break;
    case '/another-page':
    echo 'Welcome to another page';
    break;
}