【问题标题】:URL Rewrite is not working in NginxURL 重写在 Nginx 中不起作用
【发布时间】:2013-10-03 02:45:21
【问题描述】:

URL 重写在 Nginx 中不起作用,操作系统是 Ubuntu 12.4 Lts

当打开 http://mvc.loc 时它正在工作 但是当我尝试打开http://mvc.loc/login 时不工作

404 未找到

nginx/1.1.19

.htaccess

<IfModule !mod_rewrite.c>
    ErrorDocument 500 "mod_rewrite must be enabled"
</IfModule>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?u=$1

mvc.loc 的虚拟主机

server {
    listen 80;
    server_name mvc.loc;
    access_log /var/log/nginx/mvc.loc.access.log;
    error_log /var/log/nginx/mvc.loc.error.log;
    root /usr/share/nginx/www/mvc;

    index       index.php;


    # use fastcgi for all php files
    # Are you sure you have this set up?
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # deny access to apache .htaccess files
    location ~ /\.ht {
     deny all;
    }

}

【问题讨论】:

    标签: .htaccess nginx ubuntu-12.04


    【解决方案1】:
    location / {    
       rewrite ^(.*)$ /index.php?u=$1 last;
    }
    

    【讨论】:

    • 我知道这个答案已经过去了,但你能解释一下吗?
    【解决方案2】:

    @NanheKumar 的回答得到了正确的重写,但它忽略了 htaccess 中的前 2 条规则

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    

    这意味着检查请求是否与文件不匹配并且不匹配目录,要模仿这种确切的行为,您可以像这样使用try_files

    location / {
        try_files $uri $uri/ /index.php?u=$request_uri;
    }
    

    这将确保首先直接处理指向资产或目录的请求,然后如果两者都不会将请求传递给index.php

    编辑:除非index.php 能够提供资产,否则这将导致所有资产(图像、css、javascript 等)显示错误,因为index.php 将收到它不期望的参数.想想这样的事情http://example.com/index.php?u=/images/background.jpg

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多