【问题标题】:Different url rewriting according to locations根据位置不同的url重写
【发布时间】:2016-07-05 22:16:26
【问题描述】:

我真的没有找到任何关于 URL 重写的文档(我无法理解,因为我意外地发现文档对于非本地人来说真的很难阅读)。

我正在寻找一种方法将所有匹配 /*\.(js|png|jpg|css|ttf|xml)$/ 的路由重写为 path/media/ 并尝试文件的存在,如果存在则返回它,否则 404 not found

如果它以/ajax/ 开头,则将其全部重定向到path/ajax/index.php 否则将所有内容重定向到path/www/index.php

我不太明白我应该怎么做,现在我创建了 3 个位置 /media/、/ajax/ 和 /www/,但我不知道这是否是使用重写而不返回的正确方法,或者这些位置是正确的方法。

我不太明白我在sites-enabled/file 中写的关于 fastcgi 的内容。这是解释器路径吗?

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

如果我没听错,意思是“如果它以.php结尾,并且存在于层次结构中,则执行它”。

而且我不知道我是否应该为每个必须处理 php 的位置(/www/ 和 /ajax/)放置这种东西,特别是因为我要为这两个位置做一些路由。而且,我不知道是否应该这样做。

【问题讨论】:

    标签: nginx url-rewriting fastcgi nginx-location


    【解决方案1】:

    最简单的 PHP 配置使用一个通用的 root 指令,该指令由位置块继承,在您的情况下是:

    root path;
    

    这意味着/www/index.php/ajax/index.php 都由location ~ \.php$ 块处理。

    默认操作可以由location / 块中的try_files 指令定义:

    location / {
        try_files $uri $uri/ /www/index.php;
    }
    

    如果您需要对以 /ajax 开头的 URI 使用不同的默认操作,请添加更具体的位置:

    location /ajax {
        try_files $uri $uri/ /ajax/index.php;
    }
    

    如果您不希望媒体 URI 以 /media 开头,您可以覆盖一个特定位置的 root

    location ~* \.(js|png|jpg|css|ttf|xml)$ {
        root path/media;
    }
    

    在您的具体情况下,fastcgi_split_path_infofastcgi_index 指令是不必要的。 include fastcgi_params; 语句应该放在任何 fastcgi_param 指令之前,以避免后者被无意覆盖:

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
    

    详情请参阅nginx documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-25
      • 2014-12-06
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多