api多版本共存nginx配置方法
by
pxz
发布于: 2018-08-20 所属分类:
php
linux
标签:
nginx
1895
<p>最近公司小程序的api, 需要多版本共存, 具体的需求是<br>访问 <code>http://api.xxx.com/</code> 访问的目录是 <code>/www/api/web/</code><br>访问 <code>http://api.xxx.com/v1</code> 访问的目录是 <code>/www/versions/v1/web</code><br>访问 <code>http://api.xxx.com/v2</code> 访问的目录是 <code>/www/versions/v2/web</code><br>…<br>当访问一个不存在的目录时, 重写到 相应的目录的 index.php文件上 例如 <code>http://api.xxx.com/v2/member/login</code> 访问到 <code>/www/versions/v2/web/index.php</code><br>当访问一个存在的文件时, 则直接运行该文件, 例如<br><code>http://api.xxx.com/v2/test.php</code> 访问到 <code>/www/versions/v2/web/test.php</code><br><code>http://api.xxx.com/v2/2018/1.jpg</code> 访问到 <code>/www/versions/v2/2018/1.jpg</code><br>…</p>
<p>在还没有做多版本共存之前, nginx的配置是这样的</p>
<pre><code>server {
charset utf-8;
client_max_body_size 128M;
sendfile off;
listen 80;
server_name api.xxx.com;
#access_log logs/host.access.log main;
root /www/api/web;
location / {
try_files $uri $uri/ /index.php$is_args$args;
index index.php index.html index.htm;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
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;
try_files $uri =404;
}
}
</code></pre><p>这是yii2推荐的nginx配置方法</p>
<p>加入了多版本共存之后, 我们加了三块配置<br>第一块通过正则匹配 .php 结尾, 作相应的目录映射<br>第二块通过正则匹配 .html,.css等静态文件, 作相应的目录映射<br>第三块通过正则匹配, 把所有带 版本号的请求, 又没被以上两块匹配到的请求, 内部重定向到index.php处理<br>注意这三块的顺序不能乱</p>
<p>加了版本号目录映射后的配置如下:</p>
<pre><code>server {
charset utf-8;
client_max_body_size 128M;
sendfile off;
listen 80;
server_name api.xxx.com;
#access_log logs/host.access.log main;
root /www/api/web;
#这里先对 .php结尾的作目录映射
location ~ /v(?<version>(\d+))/(?<after_ali>(.*)\.(php|php5)$) {
root /www/api/versions/v$version/web;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/${after_ali};
}
#这里对静态文件作目录映射
location ~ /v(?<version>(\d+))/(?<after_ali>(.*)\.(html|js|css|jpg|jpeg|gif|png)$) {
alias /www/api/versions/v$version/web/$after_ali;
}
#其它带版本号的请求内部重定向到 index.php
location ~ /v(?<version>(\d+))/(?<after_ali>(.*)$) {
rewrite ^/v(\d+)/(.*)$ /v$version/index.php last;
}
#不带版本号的请求, 沿用yii2推荐的配置
location / {
try_files $uri $uri/ /index.php$is_args$args;
index index.php index.html index.htm;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
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;
try_files $uri =404;
}
}
</code></pre><p>在写这个配置时, 做了很多的尝试, 其中一个问题困扰了我比较长的时间, 这个问题是,<br>在做alias目录映射时, 链接地址会被301重定向到一个目录, 具体的原因分析, 可以查看我的另一篇文章 <a href="http://www.sgzhang.com/article/30.html" title="nginx alias别名配置为什么会出现重定向">nginx alias别名配置为什么会出现重定向</a></p>