nginx配置html与php映射解析

[toc]

需求描述

  • 以html结尾的文件请求如果系统存在对应html文件则解析,否则转为php文件解析,否则统一转index.php解析

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
map $request_filename $jx_file {
default $request_filename;
~^(.*)\.html$ $1.php;
}

server {
listen 80;
server_name flow.jx.com;
index index.html index.php;
root /Users/xingqiba/workspace/jx/flow/server/htdoc;

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

if ($request_method = 'OPTIONS') {
return 204;
}

location = /favicon.ico {
access_log off;
}

location / {
try_files $uri $uri/ /index.php?_path=$uri&$args;
}

#.html结尾的请求首先判断文件是否存在,存在则使用否则改成以.php结尾的文件,如果不存在则统一给index.php处理
location ~ ^/(.*)\.html$ {
if (-f $request_filename) {
break;
}

if (!-f $jx_file) {
rewrite ^(.*)\.html$ /index.php?_path=$1 last;
}

rewrite ^(.*)\.html$ $1.php last;
}

#.php结尾的如果不存在,则改交index.php处理
location ~ ^.+\.php {
# should have two captures
# the first becomes a value of the $fastcgi_script_name variable
# the second becomes a value of the $fastcgi_path_info variable
# example /show.php/article/0001 request
# SCRIPT_FILENAME => $fastcgi_script_name => /path/to/php/show.php
# PATH_INFO => $fastcgi_path_info => /article/0001
#fastcgi_split_path_info ^(.+?\.php)(/.*)$;

# DOCUMENT_ROOT => $document_root => /var/www
# SCRIPT_FILENAME => $document_root$fastcgi_script_name => /var/www/test.php
# SCRIPT_NAME => $fastcgi_script_name => /test.php
# REQUEST_URI => $request_uri => /test.php/foo/bar.php?v=1
# DOCUMENT_URI => $document_uri => /test.php/foo/bar.php
if (!-f $document_root$fastcgi_script_name) {
return 404;
}

#fastcgi_param PATH_INFO $fastcgi_path_info;

fastcgi_pass 127.0.0.1:9000;
include fastcgi.conf;
}
}