search
HomeOperation and MaintenanceNginxWhat are the common configurations and techniques of Nginx?

一个站点配置多个域名

server {
 listen 80;
 server_name ops-coffee.cn b.ops-coffee.cn;
}

server_name 后跟多个域名即可,多个域名之间用空格分隔

一个服务配置多个站点

server {
 listen 80;
 server_name a.ops-coffee.cn;

 location / {
 root /home/project/pa;
 index index.html;
 }
}

server {
 listen 80;
 server_name ops-coffee.cn b.ops-coffee.cn;

 location / {
 root /home/project/pb;
 index index.html;
 }
}

server {
 listen 80;
 server_name c.ops-coffee.cn;

 location / {
 root /home/project/pc;
 index index.html;
 }
}

基于nginx虚拟主机配置实现,nginx有三种类型的虚拟主机

基于ip的虚拟主机: 需要你的服务器上有多个地址,每个站点对应不同的地址,这种方式使用的比较少

基于端口的虚拟主机: 每个站点对应不同的端口,访问的时候使用ip:port的方式访问,可以修改listen的端口来使用

基于域名的虚拟主机: 使用最广的方式,上边例子中就是用了基于域名的虚拟主机,前提条件是你有多个域名分别对应每个站点,server_name填写不同的域名即可

nginx添加账号密码验证

server {
 location / {
 auth_basic "please input user&passwd";
 auth_basic_user_file key/auth.key;
 }
}

有很多服务通过nginx访问,但本身没有提供账号认证的功能,就可以通过nginx提供的authbase账号密码认证来实现,可以用以下脚本来生成账号的密码

# cat pwd.pl 
#!/usr/bin/perl
use strict;

my $pw=$argv[0] ;
print crypt($pw,$pw)."\n";

使用方法:

# perl pwd.pl ops-coffee.cn
opf8bimqcaxww
# echo "admin:opf8bimqcaxww" > key/auth.key

nginx开启列目录

当你想让nginx作为文件下载服务器存在时,需要开启nginx列目录

server {
 location download {
  autoindex on;

  autoindex_exact_size off;
  autoindex_localtime on;
 }
}

autoindex_exact_size: 为on(默认)时显示文件的确切大小,单位是byte;改为off显示文件大概大小,单位kb或mb或gb

autoindex_localtime: 为off(默认)时显示的文件时间为gmt时间;改为on后,显示的文件时间为服务器时间

默认当访问列出的txt等文件时会在浏览器上显示文件的内容,如果你想让浏览器直接下载,加上下边的配置

if ($request_filename ~* ^.*?\.(txt|pdf|jpg|png)$) {
 add_header content-disposition 'attachment';
}

配置默认站点

server {
 listen 80 default;
}

当一个nginx服务上创建了多个虚拟主机时默认会从上到下查找,如果匹配不到虚拟主机则会返回第一个虚拟主机的内容,如果你想指定一个默认站点时,可以将这个站点的虚拟主机放在配置文件中第一个虚拟主机的位置,或者在这个站点的虚拟主机上配置listen default

不允许通过ip访问

server {
 listen  80 default;
 server_name _;

 return  404;
}

可能有一些未备案的域名或者你不希望的域名将服务器地址指向了你的服务器,这时候就会对你的站点造成一定的影响,需要禁止ip或未配置的域名访问,我们利用上边所说的default规则,将默认流量都转到404去

上边这个方法比较粗暴,当然你也可以配置下所有未配置的地址访问时直接301重定向到你的网站去,也能为你的网站带来一定的流量

server {
 rewrite ^/(.*)$ https://ops-coffee.cn/$1 permanent;
}

直接返回验证文件

location = /xdfyle6tna.txt {
 default_type text/plain;
 return 200 'd6296a84657eb275c05c31b10924f6ea';
}

很多时候微信等程序都需要我们放一个txt的文件到项目里以验证项目归属,我们可以直接通过上边这种方式修改nginx即可,无需真正的把文件给放到服务器上

nginx配置upstream反向代理

http {
 ...
 upstream tomcats {
  server 192.168.106.176 weight=1;
  server 192.168.106.177 weight=1;
 }

 server {
  location /ops-coffee/ { 
   proxy_pass http://tomcats;

   proxy_set_header host $host;
   proxy_set_header x-real-ip $remote_addr;
   proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
   proxy_set_header x-forwarded-proto $scheme;
  }
 }

}

稍不注意可能会落入一个proxy_pass加杠不加杠的陷阱,这里详细说下proxy_pass http://tomcats与proxy_pass http://tomcats/的区别:

虽然只是一个/的区别但结果确千差万别。分为以下两种情况:

1.  目标地址中不带uri(proxy_pass http://tomcats)。此时新的目标url中,匹配的uri部分不做修改,原来是什么就是什么。

location /ops-coffee/ {
 proxy_pass http://192.168.106.135:8181;
}

http://domain/ops-coffee/ -->  http://192.168.106.135:8181/ops-coffee/
http://domain/ops-coffee/action/abc -->  http://192.168.106.135:8181/ops-coffee/action/abc

2.  目标地址中带uri(proxy_pass http://tomcats/,/也是uri),此时新的目标url中,匹配的uri部分将会被修改为该参数中的uri。

location /ops-coffee/ {
 proxy_pass http://192.168.106.135:8181/;
}

http://domain/ops-coffee/ -->  http://192.168.106.135:8181
http://domain/ops-coffee/action/abc -->  http://192.168.106.135:8181/action/abc

nginx upstream开启keepalive

upstream tomcat {
 server ops-coffee.cn:8080;
 keepalive 1024;
}

server {
 location / {
  proxy_http_version 1.1;
  proxy_set_header connection "";

  proxy_pass http://tomcat;
 }
}

nginx在项目中大多数情况下会作为反向代理使用,例如nginx后接tomcat,nginx后接php等,这时我们开启nginx和后端服务之间的keepalive能够减少频繁创建tcp连接造成的资源消耗,配置如上

keepalive: 指定每个nginxworker可以保持的最大连接数量为1024,默认不设置,即nginx作为client时keepalive未生效

proxy_http_version 1.1: 开启keepalive要求http协议版本为http 1.1

proxy_set_header connection "": 为了兼容老的协议以及防止http头中有connection close导致的keepalive失效,这里需要及时清掉http头部的connection

404自动跳转到首页

server {
 location / {
  error_page 404 = @ops-coffee;
 }

 location @ops-coffee {
  rewrite .* / permanent;
 }
}

网站出现404页面不是特别友好,我们可以通过上边的配置在出现404之后给自动跳转到首页去

The above is the detailed content of What are the common configurations and techniques of Nginx?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX Unit's Purpose: Running Web ApplicationsNGINX Unit's Purpose: Running Web ApplicationsApr 30, 2025 am 12:06 AM

The purpose of NGINXUnit is to simplify the deployment and management of web applications. Its advantages include: 1) Supports multiple programming languages, such as Python, PHP, Go, Java and Node.js; 2) Provides dynamic configuration and automatic reloading functions; 3) manages application lifecycle through a unified API; 4) Adopt an asynchronous I/O model to support high concurrency and load balancing.

NGINX: An Introduction to the High-Performance Web ServerNGINX: An Introduction to the High-Performance Web ServerApr 29, 2025 am 12:02 AM

NGINX started in 2002 and was developed by IgorSysoev to solve the C10k problem. 1.NGINX is a high-performance web server, an event-driven asynchronous architecture, suitable for high concurrency. 2. Provide advanced functions such as reverse proxy, load balancing and caching to improve system performance and reliability. 3. Optimization techniques include adjusting the number of worker processes, enabling Gzip compression, using HTTP/2 and security configuration.

NGINX vs. Apache: A Look at Their ArchitecturesNGINX vs. Apache: A Look at Their ArchitecturesApr 28, 2025 am 12:13 AM

The main architecture difference between NGINX and Apache is that NGINX adopts event-driven, asynchronous non-blocking model, while Apache uses process or thread model. 1) NGINX efficiently handles high-concurrent connections through event loops and I/O multiplexing mechanisms, suitable for static content and reverse proxy. 2) Apache adopts a multi-process or multi-threaded model, which is highly stable but has high resource consumption, and is suitable for scenarios where rich module expansion is required.

NGINX vs. Apache: Examining the Pros and ConsNGINX vs. Apache: Examining the Pros and ConsApr 27, 2025 am 12:05 AM

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache: Understanding the Key DifferencesNGINX and Apache: Understanding the Key DifferencesApr 26, 2025 am 12:01 AM

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINX Unit: Key Features and CapabilitiesNGINX Unit: Key Features and CapabilitiesApr 25, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports multiple programming languages ​​and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

NGINX Unit vs. Other Application ServersNGINX Unit vs. Other Application ServersApr 24, 2025 am 12:14 AM

NGINXUnit is better than ApacheTomcat, Gunicorn and Node.js built-in HTTP servers, suitable for multilingual projects and dynamic configuration requirements. 1) Supports multiple programming languages, 2) Provides dynamic configuration reloading, 3) Built-in load balancing function, suitable for projects that require high scalability and reliability.

NGINX Unit: The Architecture and How It WorksNGINX Unit: The Architecture and How It WorksApr 23, 2025 am 12:18 AM

NGINXUnit improves application performance and manageability with its modular architecture and dynamic reconfiguration capabilities. 1) Modular design includes master processes, routers and application processes, supporting efficient management and expansion. 2) Dynamic reconfiguration allows seamless update of configuration at runtime, suitable for CI/CD environments. 3) Multilingual support is implemented through dynamic loading of language runtime, improving development flexibility. 4) High performance is achieved through event-driven models and asynchronous I/O, and remains efficient even under high concurrency. 5) Security is improved by isolating application processes and reducing the mutual influence between applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools