【问题标题】:htaccess rewrite rules in Nginx: setting the rewrite pathNginx中的htaccess重写规则:设置重写路径
【发布时间】:2012-11-19 02:13:56
【问题描述】:

我有一个 htaccess 文件,我正在尝试将其转换为 nignx 配置文件。

这是我的 htaccess 文件。

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule    !\.(jpg|css|js|gif|png)$    public/    [L]
RewriteRule !\.(jpg|css|js|gif|png)$ public/index.php?url=$1

以及我在 nginx 配置文件中的规则:

location / {
if ($request_uri !~ "-f"){
        rewrite !\.(jpg|css|js|gif|png)$ public/ break;
}
rewrite !\.(jpg|css|js|gif|png)$ public/index.php?url=$1;
}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
        # Move to the @missing part when the file doesn't exist
        try_files $uri @missing;

        # Fix for server variables that behave differently under nginx/$
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # Include the standard fastcgi_params file included with ngingx
        include fastcgi_params;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_index index.php;


        # Pass to upstream PHP-FPM; This must match whater you name you$
        #fastcgi_pass phpfpm;
        fastcgi_pass 127.0.0.1:9000;
}

location @missing {
        rewrite ^(.*)$ public/index.php?url=$1 break;
}

但是,当我点击 / 时,我得到了 403 Forbidden,但我可以访问 /public/index.php,因此重写不起作用。

关于我做错了什么有什么想法吗?

【问题讨论】:

    标签: nginx rewrite


    【解决方案1】:

    您的if ($request_uri !~ "-f")-statement 不会按照您在 nginx 中的要求进行解析。您不是在检查文件是否存在,而是在与否定的正则表达式 -f 进行匹配。要在 nginx 的 if 中检查文件是否存在,请使用 if ( -f $request_filename )

    有关 nginx if 语句的完整详细信息,请参阅 http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#if

    通常你想替换常见的 .htaccess 节:

    RewriteEngine on
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteRule    <regex>    <target>
    

    使用 nginx 等效项:

    location ~* <regex> { try_files $uri $uri/ <target>;}
    

    对于您声明的位,您将获得如下嵌套位置:

    location / {
      location ~* \.(jpg|css|js|gif|png)$ { try_files $uri $uri/ /public/; }
      location !~* (.*)\.(jpg|css|js|gif|png)$ { 
        try_files $uri $uri/ /public/index.php?url=$1; 
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      • 2016-08-09
      • 2014-04-24
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      相关资源
      最近更新 更多