繁体   English   中英

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

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

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

我相信这正是Nginx Rewrite Module的目的,但是我在理解文档时遇到了麻烦,而且我无法使其按预期的方式工作。 因此,在这一点上,我在质疑我对模块的理解是否正确。

这是我想要实现的最简单的结果:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM