Nginx 简单使用

安装

sudo apt install nginx-full 如果之前安装过 apache2, 建议先卸载掉…… 如果没有意外的话,打开 http://localhost/ 就可以看到默认欢迎页了。

配置

安装后配置文件都在 /etc/nginx 下。打开 nginx.conf 可以看到,会把 conf.d 文件夹下所有的 *.conf 文件都包含进来。因此我们可以把自定义配置文件放在 conf.d 目录下。 这里假设我们需要配置一个域名:youthlin.local, 于是我在 conf.d 目录下新建一个文件 youthlin.local.conf, 文件名任意,conf 结尾就行。然后键入内容:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#upstream 表示实际的地址
upstream youthlin_local{
	server 127.0.0.1:8080;
	server 127.0.0.1:8081;
}

server {
	listen 80;
	listen [::]:80;
    #域名
	server_name youthlin.local;

	location / {
	    #真实IP,Java里就可以使用【request.getHeader("X-Real-IP")】获取IP
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header Host $host;
		#上游真实地址
		proxy_pass http://youthlin_local;
		try_files $uri $uri/ =404;
	}
}

测试

打开 IDEA,写个测试页面:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page trimDirectiveWhitespaces="true" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
Index<br>
<%=application%><br>
<%=request.getHeader("X-Real-IP")%>
</body>
</html>
用 Debug 起一个Tomcat,然后用 Maven 插件 tomcat7 起一个实例(mvn tomcat7:run):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                    <port>8081</port>
                    <server>tomcat7</server>
                    <finalName>ROOT</finalName>
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
现在可以通过127.0.0.1:8080 和 127.0.0.1:8081 访问两个实例了。 配置 hosts:127.0.0.1 youthlin.local 然后打开 youthlin.local 就成功了~

Reader Echoes

3 comments

  • #1440c
    坏笑 貌似配置文件非.conf结尾也行 PS. 烦请老哥帮忙把友链改回“秋空(qiukong.com)” 图库转交了我好友管理,链接保持同步~ 感谢!!
    • #1441Youth.霖
      回复 @c已更新 呲牙
    • #1443mzx
      回复 @c分放在哪个目录下面,conf.d目录下必须有结尾

表情

评论提交后需经审核才会显示。