SPA应用开启history模式的部署

SPA应用开启history模式且部署在二级目录下时nginx和apache服务器配置

作者 拓荒 日期 2019-05-17

修改vue的路由配置

1、修改router.js文件中的mode为history模式,并且设置好对应的base选项(部署时目录的名称)

export default new Router({
base: "/m/",
mode: "history",
routes: []
})

修改服务器配置文件

1、修改nginx服务器配置文件,找到站点对应的配置文件做如下修改

server {
listen 80;
server_name www.domain.com ;
root "/www/wwwroot/xxx";
location / {
index index.html index.htm index.php;
if (!-e $request_filename){
rewrite ^(.*)$ /index.php?s=$1 last; break;
}
}
location /m {
try_files $uri $uri/ /m/index.html;
}
location ~ \.php(.*)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}

以上文件添加内容为:

location /m {
try_files $uri $uri/ /m/index.html;
}

1、修改apache服务器配置文件,打开站点根目录的.htaccess文件,添加以下内容

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(m+.*)$ /m/index.html [L]
</IfModule>

注:如果网站之前配置过伪静态,好像不能在之前的配置内容添加RewriteRule ^(m+.*)$ /m/index.html [L],需要在其原有内容上面添加上面一整块代码

还有一种方案,前端页面单独部署,绑定域名可以使用接口的域名但是要修改端口号,例如:接口域名:www.api.com,前端页面绑定域名:www.api.com:81,或者使用其他域名,这个时候需要配置接口域名所对应的程序的反向代理,配置如下:

apache:

<IfModule mod_proxy.c>
ProxyRequests Off
SSLProxyEngine on
ProxyPass /m http://www.api.com:81/
ProxyPassReverse /m http://www.api.com:81/
</IfModule>

nginx:

location /m/ {
proxy_pass http://www.api.com:81/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

然后将www.api.com/m代理到www.api.com:81,同时前端项目所在网站需要如下设置:
apache:

 <IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.html [L]
</IfModule>

nginx:

location /m {
try_files $uri $uri/ /index.html;
}

第二种方案相对第一种接口请求要慢不少,应为中间有个代理层,我估计如果在服务器内部将项目域名用host指向本地应该回合第一种速度差不多,毕竟代理直接就走内网了。
(完)