如何使用Nginx重写模块更改请求URI?

时间:2015-09-22 17:31:43

标签: php nginx rewrite friendly-url

我想使用单个PHP文件,该文件使用请求的URI来决定要显示的内容,同时确保该URL是用户友好的。前者很容易实现,但是当我尝试实现后者时遇到了麻烦。

我相信这正是Nginx Rewrite Module所做的事情,但我无法理解文档,我无法按照我期望的方式工作。所以在这一点上,我质疑我对模块的理解是否正确。

这是我想要实现的目标,最简单的是:

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

    以下是我尝试这样做的方法:

    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等等。我总是首先使用{{检查我的正则表达式来完成这些操作3}}然后重新加载Nginx配置文件。无论如何,我得到了500错误,或者URI保持不变。

1 个答案:

答案 0 :(得分:0)

您可以使用以下配置尝试实现的目标:

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;
}