Nginx配置文件详细说明以及案例
参考资料
Nginx配置文件通常位于/etc/nginx/nginx.conf或/usr/local/nginx/conf/nginx.conf,其结构主要包括以下几个部分:
全局块:配置影响Nginx全局的指令,如用户、工作进程数、错误日志等。
user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid;
events块:配置影响Nginx服务器与客户端网络连接的指令。
events { worker_connections 1024; }http块:配置HTTP服务器的主要部分,包括多个server块。
http { include /etc/nginx/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 /var/log/nginx/access.log main; sendfile on; keepalive_timeout 65; include /etc/nginx/conf.d/*.conf; }server块:配置虚拟主机的相关参数,一个http块可以包含多个server块。
server { listen 80; server_name example.com; location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }location块:配置请求的路由,处理特定URL的请求。
location /images/ { root /data; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; }
案例:一个简单的Nginx配置文件示例,用于托管一个静态网站。
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name example.com;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}这个配置文件定义了一个Nginx服务器,监听80端口,托管位于/usr/share/nginx/html目录下的静态网站文件。如果访问example.com,Nginx会返回index.html或index.htm文件。如果发生500、502、503或504错误,Nginx会返回50x.html文件。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . 宝塔 | 西里网》 -- 发布时间:2025-03-29
本页链接:https://bt.ciilii.com/show/news-58.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
