Nginx 服务器配置 - 重写问题

Nginx 服务器配置 - 重写问题

我有以下服务器配置:

server {
    listen       80;
    server_name  mysite.proj;

    location / {
        root /path/to/mysite.proj/www;
        index index.php index.html index.htm;
    }

    access_log /path/to/mysite.proj/data/logs/access.log;
    error_log  /path/to/mysite.proj/data/logs/error.log;

    if (!-e $request_filename) {
        rewrite ^(.+)$ /index.php last;
    }

    location ~ \.php$ {
        root           /path/to/mysite.proj/www;
        fastcgi_pass   127.0.0.1:8081;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /path/to/mysite.proj/www$fastcgi_script_name;
        include        fastcgi_params;
    }
}

server {
    listen 80;
    server_name www.mysite.proj;
    rewrite ^/(.*) http://mysite.proj/$1 permanent;
}

一切正常,每个 URL 都被重写为 index.php。但同时每个样式表 URL、每个 javascript URL、每个图像 URL 也被重写。如何编写重写规则以不重写 css、js、图像文件的 URL?

答案1

您没有在服务器上下文中设置根,而 if 就位于该上下文中,因此它使用默认的 <install prefix>/html。您应该将根移至服务器上下文,并将 if 替换为 try_files。此外,没有必要在无 www 重定向中捕获请求,因为原始请求已存储在 $request_uri 中。

server {
    listen 80;
    server_name www.mysite.proj;
    # Permanent redirect to no-www
    return 301 http://mysite.proj$request_uri;
}

server {
    listen 80;
    server_name mysite.proj;

    root /path/to/mysite.proj/www;
    index index.php index.html index.htm;

    access_log /path/to/mysite.proj/data/logs/access.log;
    error_log  /path/to/mysite.proj/data/logs/error.log;

    location / {
        # try_files does not preserve query string by default like rewrite
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        # If the requested file doesn't exist, and /index.php doesn't, return a 404
        try_files $uri /index.php =404;

        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_pass   127.0.0.1:8081;
    }
}

相关内容