如果存在,则 Nginx 提供纯文件,否则提供 /index.php

Joh*_*ave 2 rewrite nginx

我希望 Nginx 自行处理对静态文件的任何请求,但如果该文件不存在,则提供 index.php 将处理所有这些请求

目前我的配置是这样的,

server {
listen 80;
listen [::]:80;

root /home/www/example.com/htdocs;

index index.php;

server_name www.example.com;


location ~* ^[^\?\&]+\.(html|jpg|jpeg|json|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|svg|woff|ttf)$ {
    # First attempt to serve request as file, then
    # as directory, then fall back to index.php
    try_files $uri $uri/ /index.php;
    #try_files /favicon.ico =404;
}


location / {
    add_header X-Is-PHP true;
            try_files /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            # With php5-fpm:
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
    }


}
Run Code Online (Sandbox Code Playgroud)

这是我所能得到的,它为任何对静态文件的请求提供服务,如果它不存在,则将 index.php 作为纯文本文件提供。如何将 index.php 传递给 PHP 解释器?

var*_*run 5

尝试这个

服务器 {
听80;
听 [::]:80;

root /home/www/example.com/htdocs;

索引 index.php;

server_name www.example.com;


位置 ~* ^[^\?\&]+\.(html|jpg|jpeg|json|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|pdf|ppt|txt |tar|mid|midi|wav|bmp|rtf|js|svg|woff|ttf)$ {
    # 首先尝试将请求作为文件提供服务,然后
    # 作为目录,然后回退到 index.php
    try_files $uri $uri//index.php;
    #try_files /favicon.ico =404;
}

error_page 404 /index.php;

位置 ~ \.php$ {
            add_header X-Is-PHP true;
            #try_files $uri =404;
            try_files /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            # 使用 php5-fpm:
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            包括 fastcgi.conf;
    }


}

变化

1) 添加error_page 404 /index.php;以便在服务器上找不到的所有请求都重定向到 index.php

2) 添加“~ .php$”到位置属性。

3) 如果您还希望解释其他 PHP 文件,请取消注释“#try_files $uri =404;”行 并注释“try_files /index.php =404;”行