安装nginx,并把静态资源放入nginx

本文指导如何在CentOS上安装EPEL仓库,通过yum安装Nginx,并配置服务、关键文件路径,包括防火墙设置、SELinux优化及前端静态资源转发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装EPEL仓库

sudo yum install -y epel-release

安装 nginx

在安装完 EPEL 仓库后,我们就可以直接使用 yum 在安装 nginx 了,命令如下:

sudo yum install -y nginx

启动nginx

在我们实际的工作中很少直接用信号控制命令来控制 nginx 服务器的启动与重启等操作。通常我们都是通过将 nginx 作为系统服务,使用 CentOS 系统的 service命令来控制 nginx 服务的启动与重启等操作。命令如下:

# 设置为系统服务
systemctl enable nginx
# 启动
service nginx start

然后就可以使用相关命令了

systemctl nginx start/stop/reload

nginx关键文件

除了上面介绍的 nginx 常用命令,使用 nignx 另外一个需要了解的基础知识就是 nginx 服务的一些关键文件的路径和作用(PS:以下这些 nginx 关键文件的路径,都是指使用 yum 直接安装 nginx 的默认路径)

  • /etc/nginx:nginx 配置文件的根目录,nginx 的所有配置文件都在这个目录下面;
  • /etc/nginx/nginx.conf:nginx 主配置文件,所有 nginx 的基础和全局配置都应该在这个文件中配置;
  • /etc/nginx/conf.d:nginx 默认站点配置文件所在目录;
  • /var/log/nginx:nginx 日志文件目录,访问日志 access.log 和 错误日志 error.log 都在这个目录中;

防火墙配置

到目前为止,我们已经启动了 nginx 服务了,不过如果想要外网能够访问我们在 nginx 服务器中配置的 Web 站点,我们还需要做一些额外的操作————那就是做防火墙配置,让 CentOS 系统对外网公开 80 端口和允许外部访问 http 服务。命令如下:

# 开启80端口
firewall-cmd --zone=public --add-port=80/tcp --permanent
# 允许外部访问http服务
firewall-cmd --zone=public --add-service=http --permanent
# 重启防火墙以生效
firewall-cmd --reload

如果你的 Web 站点启用 HTTPS 协议,那么你还需要让防火强对外公开 443 端口和 https 服务。

# 开启443端口
firewall-cmd --zone=public --add-port=443/tcp --permanent
# 允许访问https服务
firewall-cmd --zone=public --add-service=https --permanent
# 重启防火墙以生效
firewall-cmd --reload

selinux配置

通常,我们都会用 nginx 服务器做反响代理设置,配置 Web 站点集群,实现站点的高可用。那么这个时候我们还需要配置 selinux 配置,允许 http 服务间的通信。

# 允许http服务间的通信
setsebool -P httpd_can_network_connect 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  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /data/project/energy/front/energy-front/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        location /platform-backend {
	  proxy_set_header Host $http_host;
	  proxy_set_header X-Real-IP $remote_addr;
	  proxy_set_header REMOTE-HOST $remote_addr;
	  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	  proxy_pass http://localhost:8081/platform-backend;
        }


        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

<think>我们首先明确用户的需求:配置Nginx作为静态资源服务器的最佳实践。根据提供的引用信息,我们可以总结出几个关键步骤和最佳实践。关键点:1.创建专门存放静态资源的目录(如引用[1]和[2]中提到的/home/dvlp1/,也可以自定义)2.修改Nginx配置文件(通常是nginx.conf或conf.d目录下的配置文件)3.配置location块来匹配静态资源请求,设置root路径4.启用目录列表(可选,如引用[3]所述,但需谨慎使用)5.设置缓存(如引用[2]中的expires指令)6.测试重新加载配置最佳实践建议:-为静态资源设置独立的server块或location块,避免干扰动态内容-使用root指令指向静态资源目录-设置缓存头以减少重复请求-关闭不必要的日志记录(如引用[2]中的access_logoff)以提升性能-启用gzip压缩(虽然引用中未提及,但这是常见优化)配置步骤:1.创建静态资源目录:```bashmkdir-p/path/to/static_resources```将静态文件(如图片、CSS、JS)放入该目录。2.编辑Nginx配置文件(如/etc/nginx/nginx.conf或/etc/nginx/conf.d/static.conf):```nginx#在http块内,可以添加一个server块专门用于静态资源server{listen80;server_nameyour_domain_or_ip;location/static/{#设置静态资源的实际路径,访问时URL会包含/static/root/path/to/;#注意:这里指定的路径是/path/to/,那么实际资源路径是/path/to/static/autoindexoff;#默认关闭目录列表,需要时开启(注意安全)expires30d;#设置缓存时间access_logoff;#关闭访问日志}#或者按文件类型匹配(如引用[2]的方式)location~*\.(?:jpg|jpeg|gif|png|ico|css|js)${root/path/to/static_resources;expires30d;access_logoff;}}```注意:两种方式可以选择一种,也可以结合使用。3.验证配置重新加载:```bashnginx-t#验证配置文件语法nginx-sreload#重新加载配置```4.访问测试:在浏览器访问:`http://your_domain_or_ip/static/example.jpg`(取决于配置的路径)安全考虑:-如果开启autoindexon(目录列表),确保该目录不包含敏感文件-静态资源服务器通常无需执行权限,因此不要配置cgi或php等处理其他优化:-启用gzip压缩(在http或server块中添加gzip相关配置)-使用sendfile提高文件传输效率(默认开启)相关问题:1.如何为不同的静态资源类型设置不同的缓存时间?2.如何配置Nginx的gzip压缩?3.如何保证静态资源服务器的安全性?</think> ### 配置 Nginx 作为静态资源服务器的最佳实践 根据引用内容和我对 Nginx 配置的经验,以下是配置静态资源服务器的完整方法和最佳实践: #### 1. **创建静态资源目录** ```bash # 创建专门存放静态资源的目录 sudo mkdir -p /home/static_resources/images sudo mkdir -p /home/static_resources/css sudo mkdir -p /home/static_resources/js ``` **最佳实践**:建议使用独立的目录结构(如 `/home/static_resources/`),避免与 Nginx 默认目录混用[^1]。 #### 2. **编辑 Nginx 配置文件** 打开配置文件(通常位于 `/etc/nginx/nginx.conf` 或 `/etc/nginx/sites-enabled/default`): ```nginx server { listen 80; server_name yourdomain.com; # 静态资源配置 (最佳实践:按类型分组) location ~* \.(jpg|jpeg|png|gif|ico|svg)$ { root /home/static_resources/images; access_log off; # 关闭访问日志 expires 30d; # 客户端缓存30天 } location ~* \.(css|js)$ { root /home/static_resources; add_header Cache-Control "public, max-age=604800"; # 缓存7天 access_log off; } # 可选:开启目录列表(谨慎使用) location /static/ { root /home/static_resources; autoindex on; # 允许列出目录内容[^3] autoindex_exact_size off; # 显示文件大小(MB/KB) } } ``` #### 3. **关键配置说明** | **指令** | **作用** | **最佳实践** | |-------------------|--------------------------------------------------------------------------|---------------------------------------| | `root` | 定义资源根目录 | 使用绝对路径,避免相对路径 | | `expires` | 设置浏览器缓存时间 | 图片建议30天,CSS/JS建议7天[^2] | | `access_log off` | 禁用访问日志 | 大幅提升性能(特别是高发场景) | | `autoindex on` | 启用目录索引 | 仅限内部网络环境[^3] | | `add_header` | 添加自定义HTTP头 | 增强缓存控制 | #### 4. **验证与重载配置** ```bash # 检查语法 sudo nginx -t # 重载配置(无需重启) sudo nginx -s reload ``` #### 5. **安全优化建议** ```nginx # 禁止敏感文件访问 location ~* \.(htaccess|env|log)$ { deny all; } # 限制访问频率(防止滥用) location ~* \.(zip|tar|gz)$ { root /home/static_resources; limit_rate_after 10m; # 10MB后限速 limit_rate 100k; # 限速100KB/s } ``` **验证方法**: 1. 浏览器访问:`http://yourdomain.com/image.png` 2. 使用 curl 检查缓存头: ```bash curl -I http://yourdomain.com/style.css ``` 应看到:`Cache-Control: public, max-age=604800` #### 6. **性能优化补充** - 启用 Gzip 压缩(在 http 块添加): ```nginx gzip on; gzip_types text/css application/javascript; ``` - 使用内存盘加速: ```nginx location /cache/ { root /dev/shm/static_cache; # 使用内存存储热点文件 } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值