在配合同学的Angular的应用的时候,他对我提出了如下要求:
/KnowledgeCuisine/*这种模式的url(比如/KnowledgeCuisine/user/login),按照你的MVC框架定义的逻辑回应
除了以上模式的url都返回给我一个index.html文档
我一开始是真不理解,其实就是如果是tomcat提供的接口,就返回接口内容,要是不是接口内容,那么就返回index.html。
一开始走了弯路,使用了tomcat的静态资源路径映射,但这个路径映射实际上就是访问静态资源的,与响应接口无关,例如你在某个文件下有一个文件a.txt,配置了静态资源访问之后,那么你可以通过浏览器http://ip:8080/文件夹/a.txt访问到a.txt内容,但不是响应接口。
这个时候就来了Nginx的反向代理。
打开Nginx目录下conf文件夹中的nginx.conf文件
server {
listen 80;
server_name localhost;
root /home/tomcat/apache-tomcat-8.5.8/webapps/ROOT;
index index.html;
#charset koi8-r;
#access_log logs/host.access.log main;
#root html;
#index index.html index.htm;
location /index.html {
rewrite ^ /index.html break;
}
location / {
#try_files $uri $uri/ /home/tomcat/apache-tomcat-8.5.8/webapps/ROOT/index.html;
# try_files $uri $uri/ =404;
try_files $uri $uri/ /index.html;
}
location ~ (^/KnowledgeCuisine){
proxy_pass http://localhost:8080;
}
location ~ \.(jsp|do)$ {
proxy_pass http://localhost:8080;
}
error_page 404 index.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
listen 80;
server_name localhost;
root /home/tomcat/apache-tomcat-8.5.8/webapps/ROOT;
index index.html;
监听 80端口,这个非常方便,与http相同,即无需输入端口即可正常访问。
root地址是包含index.html文件夹的地址
若是想相应接口
那么使用模糊匹配,我的接口的url都是以/KnowledgeCuisine开头的,例如/KnowledgeCuisine/user/login,/KnowledgeCuisine换成你自己的tomcat项目名。
location ~ (^/KnowledgeCuisine){
proxy_pass http://localhost:8080;
}
这样就可以通过Nginx访问tomcat接口。
那对于其它的访问
location / {
try_files $uri $uri/ /index.html;
}
使用这一个命令即可,由于路径匹配是最长匹配,而不是贪心匹配,所以当/KnowledgeCuisine/user/login传来的时候,匹配的是/KnowledgeCuisine,而不是/,而对于/user/login,匹配的就是/,这个时候返回/index.html,记得写/,不然会有错误。
如果还有问题,一定要仔细阅读Nginx目录下log里面的error.log,可以发现错误,方便debug。