安裝nginx參考本人另一篇博客:http://www.cnblogs.com/gmq-sh/p/5750833.html
spring-boot需要啟動nginx的,用於監聽啟動的端口。
一、配置nginx:
#user nobody;
worker_processes 1;
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name testgmq.com; #域名
index myindex.html; #指定的server的root的訪問頁面
root /home/www/index; #指定的server的root目錄
#charset koi8-r;
#access_log logs/host.access.log main;
#我工程的context-path=mytest
location /mytest {
proxy_pass http://localhost:8080;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Port $server_port;
# root html;
# index index.html index.htm;
}
}
}
這里有三點需要說明:
1、nginx允許一個server同時支持http和https兩種協議。這里我們分別定義了http:80和https:443兩個協議和端口號。如果你不需要http:80則可刪除那行。
2、nginx收到請求后將通過http協議轉發給tomcat。由於nginx和tomcat在同一台機里因此nginx和tomcat之間無需使用https協議。
3、由於對tomcat而言收到的是普通的http請求,因此當tomcat里的應用發生轉向請求時將轉向為http而非https,為此我們需要告訴tomcat已被https代理,方法是增加X-Forwared-Proto和X-Forwarded-Port兩個HTTP頭信息。
二、接着再配置tomcat。基於spring-boot開發時只需在application.properties中進行配置:
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
server.tomcat.port-header=X-Forwarded-Port
server.use-forward-headers=true
該配置將指示tomcat從HTTP頭信息中去獲取協議信息(而非從HttpServletRequest中獲取),同時,如果你的應用還用到了spring-security則也無需再配置。
此外,由於spring-boot足夠自動化,你也可以把上面四行變為兩行:
server.tomcat.protocol_header=x-forwarded-proto
server.use-forward-headers=true
下面這樣寫也可以:
server.tomcat.remote_ip_header=x-forwarded-for
server.use-forward-headers=true
但不能只寫一行:
server.use-forward-headers=true
具體請參見http://docs.spring.io/spring-boot/docs/1.3.0.RELEASE/reference/htmlsingle/#howto-enable-https,其中說到:
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
The presence of either of those properties will switch on the valve
此外,雖然我們的tomcat被nginx反向代理了,但仍可訪問到其8080端口。為此可在application.properties中增加一行:
server.address=127.0.0.1
這樣一來其8080端口就只能被本機訪問了,其它機器訪問不到。
我是springboot,加了context-path=myproject,但是我綁定的域名又想:www.myxxx.com直徑訪問我項目中的其中的一個url,所以:
在server_name下面增加了:index,root兩個配置。
/home/www/index/myindex.html:
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> <!-- 特定的url作為首頁 --> window.location.href = "http://www.myxxx.com/myproject/mobile/shopindex.html"; </script> </body> </html>
作為跳轉的處理。
如果有更好的方法,可以互相交流。