knowledge/technology/applications/web/nginx.md
2023-12-04 11:02:23 +01:00

86 lines
2.4 KiB
Markdown

---
obj: application
website: https://nginx.org
repo: https://hg.nginx.org/nginx
---
# nginx
Nginx is a powerful open-source web server and reverse proxy server. It is widely used for serving static content, handling dynamic content through various modules, and acting as a load balancer.
## Docker Compose
```yml
version: '3'
services:
nginx:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./html:/usr/share/nginx/html:ro
- ./nginx-custom.conf:/etc/nginx/conf.d/custom.conf:ro
restart: always
```
## Configuration
Nginx's configuration is defined in the `/etc/nginx/nginx.conf` file.
### Server Blocks (Virtual Hosts)
Nginx uses server blocks to define different virtual hosts. Each server block can have its own configuration, allowing Nginx to serve multiple websites on the same server.
Example of a basic server block:
```nginx
server {
listen 80;
listen 443 ssl;
ssl_certificate certs/example.com.crt;
ssl_certificate_key certs/example.com.key;
server_name example.com www.example.com;
location / {
root /var/www/example;
index index.html;
}
# Additional configuration can go here
}
```
In this example:
- `listen`: Specifies the port on which Nginx will listen for incoming requests.
- `server_name`: Defines the [domain](../../internet/Domain.md) names for this server block.
- `location`: Configures how Nginx processes requests for the specified location.
### Locations
The location directive is used to configure how Nginx handles different types of requests. It can be used for [URL](../../internet/URL.md) matching, proxying, and more.
Example of a location block:
```nginx
location /images/ {
alias /var/www/example/images/;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
```
In this example:
- `alias`: Maps a location to a filesystem path.
- `expires`: Sets the cache expiration for the specified location.
- `add_header`: Adds custom [HTTP](../../internet/HTTP.md) headers to the response.
### Reverse Proxy
Nginx can act as a reverse proxy to forward requests to other servers.
Example of a reverse proxy configuration:
```nginx
location /app/ {
proxy_pass http://backend-server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
```
In this example:
- `proxy_pass`: Specifies the backend server's address.
- `proxy_set_header`: Sets custom headers for the proxy request.