当前位置: 技术文章>> magento2中的Nginx配置以及代码示例

文章标题:magento2中的Nginx配置以及代码示例
  • 文章分类: Magento
  • 10828 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


以下是一个Magento 2的Nginx配置示例,其中包含一些常见的最佳实践:

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

# HTTPS server
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /path/to/certificate.pem;
    ssl_certificate_key /path/to/privatekey.pem;    # Set secure SSL protocols and ciphers
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;    # Enable HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload;" always;    # Set Magento root directory
    root /path/to/magento;    # Magento specific Nginx configuration
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location /pub/static/versioned/ {
        # Set cache headers
        expires 1y;
        add_header Cache-Control "public";

        # Magento specific Nginx configuration
        try_files $uri $uri/ /pub/static.php?$args;
    }

    location /static/ {        # Set cache headers
        expires 1y;
        add_header Cache-Control "public";        # Magento specific Nginx configuration
        try_files $uri $uri/ /static.php?$args;
    }

    location /media/ {
        # Set cache headers
        expires 1y;
        add_header Cache-Control "public";

        # Magento specific Nginx configuration
        try_files $uri $uri/ /get.php?$args;
    }

    location /errors/ {        # Disable access to error pages
        deny all;        return 404;
    }    # Redirect server error pages to the static page /50x.html
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    # Serve static content directly
    location /static/version {
        # Set cache headers
        expires 1y;
        add_header Cache-Control "public";

        # Serve content directly
        try_files $uri =404;
    }

    # Disable access to sensitive files
    location /app/                { deny all; }
    location /downloader/         { deny all; }
    location /lib/                { deny all; }
    location /phpserver/          { deny all; }
    location /pkginfo/            { deny all; }
    location /report/config.xml   { deny all; }
    location /var/                { deny all; }
}

此配置文件包含两个服务器块:一个HTTP服务器块,用于将HTTP请求重定向到HTTPS,以及一个HTTPS服务器块,用于配置Magento 2的Nginx。

HTTPS服务器块中的一些重要配置包括:

  • SSL证书和私钥文件的路径

  • 选择安全的SSL协议和密码

  • 启用HSTS(HTTP严格传输安全)来提高安全性

  • Magento的特定位置配置,例如:pub/static/,static/,media/等


推荐文章