当前位置:迷你笔记 » 技术 » 如何为 Magento 1.x 配置 Nginx 服务器?

如何为 Magento 1.x 配置 Nginx 服务器?

在部署 Magento 网站时,使用 Nginx 作为 Web 服务器是一种高性能的选择。本文将手把手教你如何配置 Nginx 以支持 Magento 的运行,包括 HTTP、HTTPS 和伪静态(美化 URL)配置,提升速度和安全性。

一、基本 HTTP 配置(端口 80)

首先设置 HTTP(80端口)的配置:

server {
    listen 80;
    server_name example.com; # 修改为你的域名或服务器IP

    access_log logs/host.access.log main;

    location / {
        root /var/www/magento;  # 修改为你的 Magento 安装目录
        index index.php index.html index.htm;

        # 推荐方式:使用 try_files 优雅处理伪静态
        try_files $uri $uri/ /index.php?$args;

        # 若你使用了 fooman-speedster 插件,可启用以下规则:
        # rewrite ^(/index.php)?/minify/([^/]+)(/.*\.(js|css))$ /lib/minify/m.php?f=$3&d=$2 last;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/magento$fastcgi_script_name;
        include fastcgi_params;
    }

    location /app/etc {
        deny all;
    }
}

📌 什么是 try_files?为什么推荐?

try_files $uri $uri/ /index.php?$args;

这行配置非常关键,它实现了现代 PHP 框架常用的“伪静态”逻辑,执行以下尝试顺序:

  1. $uri:如果访问的路径是实际存在的文件,则直接返回;
  2. $uri/:如果是实际存在的目录,也直接访问;
  3. /index.php?$args:否则将请求交给 index.php 并保留原参数。

示例:
请求:/products/view?id=123
若该路径不是文件或目录,Nginx 会自动转向:/index.php?id=123,由 Magento 自行解析路由。

这比使用多个 ifrewrite 更高效,也更符合 Nginx 的最佳实践。

二、启用 HTTPS 配置(端口 443)

申请并安装 SSL 证书后,可以启用 HTTPS:

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /usr/local/nginx/conf/ssl/server.crt;
    ssl_certificate_key /usr/local/nginx/conf/ssl/server.key;

    location / {
        root /var/www/magento;
        index index.php index.html index.htm;

        try_files $uri $uri/ /index.php?$args;

        # rewrite ^(/index.php)?/minify/([^/]+)(/.*\.(js|css))$ /lib/minify/m.php?f=$3&d=$2 last;
    }

    location ~ \.php$ {
        root /var/www/magento;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;

        fastcgi_param HTTPS on;  # 防止 HTTPS 访问产生重定向问题
        fastcgi_param SCRIPT_FILENAME /var/www/magento$fastcgi_script_name;

        include fastcgi_params;
    }

    location /app/etc {
        deny all;
    }
}

三、建议增强项

1. 自动跳转到 HTTPS

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

2. 增强安全性:屏蔽敏感文件

location ~* /(composer\.json|composer\.lock|\.git|\.svn|\.env|README\.md) {
    deny all;
}

3. 性能优化建议(可选)

  • 开启 Gzip 压缩
  • 使用 CDN 加速静态资源
  • 使用 Redis / Varnish 缓存加速

四、检查配置并重启 Nginx

执行以下命令确保 Nginx 配置正确:

nginx -t               # 检查配置文件语法是否正确
systemctl reload nginx  # 重载服务使配置生效

结语

以上就是 Magento 在 Nginx 上的完整配置方案。我们推荐使用 try_files 来实现 URL 重写,代替老旧的 ifrewrite 写法,以确保高性能和更易维护的结构。

你可以直接将上述配置保存为 /etc/nginx/conf.d/magento.conf,或添加到你当前的 Nginx 虚拟主机配置中。

未经允许不得转载:迷你笔记 » 如何为 Magento 1.x 配置 Nginx 服务器?

相关文章

评论 (0)

7 + 6 =