ubuntu 22.04 LTS 上 nginx 与 php-fpm 的连接问题

ubuntu 22.04 LTS 上 nginx 与 php-fpm 的连接问题

我无法访问我的网站,该网站是在新安装的 ubuntu server 22.04 LTS 上设置的。不幸的是,我的连接尝试超时并出现错误 522,我不知道从哪里开始查找问题。因此,我将解释我到目前为止所做的工作以及我已经检查过的内容。如果您能提供关于下一步可能采取的步骤的任何意见,我将不胜感激!

提前感谢您的帮助。我们非常感激。

  1. 我开始使用全新的 ubuntu 22.04 LTS,并开始安装 php8.1-fpm 和来自 ppa:ondrej/php 的一些补充包

    apt install php8.1-fpm php8.1-json php8.1-zip php8.1-gd php8.1-mbstring php8.1-curl php8.1-xml php-pear libtool

  2. 下一步安装nginx:

    curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null“
    OS=$(lsb_release -is | tr '[:upper:]' '[:lower:]')
    RELEASE=$(lsb_release -cs)
    echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
    http://nginx.org/packages/${OS} ${RELEASE} nginx" \
    | tee /etc/apt/sources.list.d/nginx.list
    apt update && apt -y upgrade && apt install -y nginx
    
  3. 安装支持 cloudflare 的 certbot 并设置 SSL 证书

    snap install core; sudo snap refresh core
    snap install --classic certbot
    ln -s /snap/bin/certbot /usr/bin/certbot
    snap set certbot trust-plugin-with-root=ok
    snap install certbot-dns-cloudflare
    mkdir /root/.secrets/ && touch /root/.secrets/cf.ini
    echo "dns_cloudflare_api_token=$cftoken" >> /root/.secrets/cf.ini
    chmod 0700 /root/.secrets/
    chmod 0600 /root/.secrets/cf.ini
    mkdir -p /etc/letsencrypt
    openssl dhparam -out /etc/letsencrypt/dhparam.pem 4096
    certbot certonly --agree-tos \
      --no-eff-email \
      --rsa-key-size 4096 \
      --dns-cloudflare \
      --dns-cloudflare-credentials /root/.secrets/cf.ini \
      --dns-cloudflare-propagation-seconds 60 \
      --preferred-challenges dns-01 \
      -m $webmail \
      -d $hostname \
      -d *.$hostname
    
    
  4. 网站目录 ($sitedir) 的设置、文件传输和权限修复

    mkdir -p /var/www/mydomain.com/public
    chown -R www-data:www-data /var/www
    find /var/www -type f -exec chmod 0640 {} \;
    find /var/www -type d -exec chmod 2750 {} \;
    
  5. 基于以下配置 nginxhttps://github.com/h5bp/server-configs-nginx

    nginx -s stop
    cd /etc
    mv nginx nginx-previous
    git clone https://github.com/h5bp/server-configs-nginx.git nginx
    cd /etc/nginx/conf.d
    cp templates/example.com.conf .mydomain.com.conf
    sed -i 's/example.com/mydomain.com/g' .mydomain.com.conf
    mv .mydomain.com.conf mydomain.com.conf
    nginx -s reload
    

    经过一些调整后,我最终得到了以下 nginx 配置

    user www-data;
    worker_processes auto;
    worker_rlimit_nofile 8192;
    events {
    
      worker_connections 8000;
    
    }
    
    # Log errors and warnings to this file
    # This is only used when you don't override it on a `server` level
    error_log /var/log/nginx/error.log warn;
    
    # The file storing the process ID of the main process
    pid /var/run/nginx/nginx.pid;
    include custom.d/*.conf;
    
    http {
    
      # Hide Nginx version information.
      include h5bp/security/server_software_information.conf;
    
      # Specify media (MIME) types for files.
      include h5bp/media_types/media_types.conf;
    
      # Set character encodings.
      include h5bp/media_types/character_encodings.conf;
    
      # Include $http_x_forwarded_for within default format used in log files
      # https://nginx.org/en/docs/http/ngx_http_log_module.html#log_format
      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;
    
      keepalive_timeout 20s;
      sendfile on;
      tcp_nopush on;
    
      # Specify file cache expiration.
      include h5bp/web_performance/cache_expiration.conf;
    
      # Add X-Frame-Options for HTML documents.
      # h5bp/security/x-frame-options.conf
      map $sent_http_content_type $x_frame_options {
        ~*text/html DENY;
      }
    
      # Add Content-Security-Policy for HTML documents.
      # h5bp/security/content-security-policy.conf
      map $sent_http_content_type $content_security_policy {
        ~*text/(html|javascript)|application/pdf|xml "default-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; object-src 'none'; upgrade-insecure-requests";
      }
    
      # Add Permissions-Policy for HTML documents.
      # h5bp/security/permissions-policy.conf
      map $sent_http_content_type $permissions_policy {
        ~*text/(html|javascript)|application/pdf|xml "accelerometer=(),autoplay=(),camera=(),display-capture=(),document-domain=(),encrypted-media=(),fullscreen=(),geolocation=(),gyroscope=(),magnetometer=(),microphone=(),midi=(),payment=(),picture-in-picture=(),publickey-credentials-get=(),screen-wake-lock=(),sync-xhr=(self),usb=(),web-share=(),xr-spatial-tracking=()";
      }
    
      # Add Referrer-Policy for HTML documents.
      # h5bp/security/referrer-policy.conf
      map $sent_http_content_type $referrer_policy {
        ~*text/(css|html|javascript)|application\/pdf|xml "strict-origin-when-cross-origin";
      }
    
      # Add Cross-Origin-Policies for HTML documents.
      # h5bp/security/cross-origin-policy.conf
      # Cross-Origin-Embedder-Policy
      map $sent_http_content_type $coep_policy {
        ~*text/(html|javascript)|application/pdf|xml "require-corp";
      }
      # Cross-Origin-Opener-Policy
      map $sent_http_content_type $coop_policy {
        ~*text/(html|javascript)|application/pdf|xml "same-origin";
      }
      # Cross-Origin-Resource-Policy
      map $sent_http_content_type $corp_policy {
        ~*text/(html|javascript)|application/pdf|xml "same-origin";
      }
    
      # Add Access-Control-Allow-Origin.
      map $sent_http_content_type $cors {
        # Images
        ~*image/ "*";
    
        # Web fonts
        ~*font/                         "*";
        ~*application/vnd.ms-fontobject "*";
        ~*application/x-font-ttf        "*";
        ~*application/font-woff         "*";
        ~*application/x-font-woff       "*";
        ~*application/font-woff2        "*";
      }
    
      include conf.d/*.conf;
    
    }
    
    # ----------------------------------------------------------------------
    # | Server software information                                        |
    # ----------------------------------------------------------------------
    server_tokens off;
    
    # ----------------------------------------------------------------------
    # | Media types                                                        |
    # ----------------------------------------------------------------------
    include mime.types;
    
    default_type application/octet-stream;
    
    # configuration file /etc/nginx/mime.types:
    types {
    
      # Data interchange
        application/atom+xml                  atom;
        application/json                      json map topojson;
        application/ld+json                   jsonld;
        application/rss+xml                   rss;
        application/geo+json                  geojson;
        application/xml                       xml;
        application/rdf+xml                   rdf;
    
      # JavaScript
        # Servers should use text/javascript for JavaScript resources.
        text/javascript                       js mjs;
        application/wasm                      wasm;
    
      # Manifest files
        application/manifest+json             webmanifest;
        application/x-web-app-manifest+json   webapp;
        text/cache-manifest                   appcache;
    
      # Media files
        audio/midi                            mid midi kar;
        audio/mp4                             aac f4a f4b m4a;
        audio/mpeg                            mp3;
        audio/ogg                             oga ogg opus;
        audio/x-realaudio                     ra;
        audio/x-wav                           wav;
        image/apng                            apng;
        image/avif                            avif avifs;
        image/bmp                             bmp;
        image/gif                             gif;
        image/jpeg                            jpeg jpg;
        image/jxl                             jxl;
        image/jxr                             jxr hdp wdp;
        image/png                             png;
        image/svg+xml                         svg svgz;
        image/tiff                            tif tiff;
        image/vnd.wap.wbmp                    wbmp;
        image/webp                            webp;
        image/x-jng                           jng;
        video/3gpp                            3gp 3gpp;
        video/mp4                             f4p f4v m4v mp4;
        video/mpeg                            mpeg mpg;
        video/ogg                             ogv;
        video/quicktime                       mov;
        video/webm                            webm;
        video/x-flv                           flv;
        video/x-mng                           mng;
        video/x-ms-asf                        asf asx;
        video/x-msvideo                       avi;
        image/x-icon                          cur ico;
    
    
      # Microsoft Office
        application/msword                                                         doc;
        application/vnd.ms-excel                                                   xls;
        application/vnd.ms-powerpoint                                              ppt;
        application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
        application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
        application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;
    
    
      # Web fonts
        font/woff                             woff;
        font/woff2                            woff2;
        application/vnd.ms-fontobject         eot;
        font/ttf                              ttf;
        font/collection                       ttc;
        font/otf                              otf;
    
      # Other
        application/java-archive              ear jar war;
        application/mac-binhex40              hqx;
        application/octet-stream              bin deb dll dmg exe img iso msi msm msp safariextz;
        application/pdf                       pdf;
        application/postscript                ai eps ps;
        application/rtf                       rtf;
        application/vnd.google-earth.kml+xml  kml;
        application/vnd.google-earth.kmz      kmz;
        application/vnd.wap.wmlc              wmlc;
        application/x-7z-compressed           7z;
        application/x-bb-appworld             bbaw;
        application/x-bittorrent              torrent;
        application/x-chrome-extension        crx;
        application/x-cocoa                   cco;
        application/x-java-archive-diff       jardiff;
        application/x-java-jnlp-file          jnlp;
        application/x-makeself                run;
        application/x-opera-extension         oex;
        application/x-perl                    pl pm;
        application/x-pilot                   pdb prc;
        application/x-rar-compressed          rar;
        application/x-redhat-package-manager  rpm;
        application/x-sea                     sea;
        application/x-shockwave-flash         swf;
        application/x-stuffit                 sit;
        application/x-tcl                     tcl tk;
        application/x-x509-ca-cert            crt der pem;
        application/x-xpinstall               xpi;
        application/xhtml+xml                 xhtml;
        application/xslt+xml                  xsl;
        application/zip                       zip;
        text/calendar                         ics;
        text/css                              css;
        text/csv                              csv;
        text/html                             htm html shtml;
        text/markdown                         md markdown;
        text/mathml                           mml;
        text/plain                            txt;
        text/vcard                            vcard vcf;
        text/vnd.rim.location.xloc            xloc;
        text/vnd.sun.j2me.app-descriptor      jad;
        text/vnd.wap.wml                      wml;
        text/vtt                              vtt;
        text/x-component                      htc;
    
    }
    
    # ----------------------------------------------------------------------
    # | Character encodings                                                |
    # ----------------------------------------------------------------------
    
    charset utf-8;
    charset_types
        text/css
        text/plain
        text/vnd.wap.wml
        text/javascript
        text/markdown
        text/calendar
        text/x-component
        text/vcard
        text/cache-manifest
        text/vtt
        application/json
        application/manifest+json;
    
      # ----------------------------------------------------------------------
      # | Config file for mydomain.com host                                   |
      # ----------------------------------------------------------------------
    
      server {
        listen 80;
        listen [::]:80;
    
        server_name www.mydomain.com mydomain.com;
    
        return 301 https://$host$request_uri;
      }
    
      server {
        listen [::]:443 ssl http2;
        listen 443 ssl http2;
    
        server_name mydomain.com;
    
        include h5bp/tls/ssl_engine.conf;
        include h5bp/tls/certificate_files.conf;
        include h5bp/tls/policy_balanced.conf;
    
        return 301 $scheme://www.mydomain.com$request_uri;
      }
    
      server {
        listen [::]:443 ssl http2;
        listen 443 ssl http2;
    
        # The host name to respond to
        server_name www.mydomain.com;
    
        include h5bp/tls/ssl_engine.conf;
        include h5bp/tls/certificate_files.conf;
        include h5bp/tls/policy_balanced.conf;
    
        # Path for static files
        root /var/www/mydomain.com/public;
        location / {
              try_files $uri $uri/ /index.php;
          }
    
        include h5bp/errors/custom_errors.conf;
        include h5bp/basic.conf;
    
        # php-fpm
        index index.php index.html;
        location ~* \.php$ {
          fastcgi_pass unix:/var/run/php8.1-fpm.sock;
          fastcgi_param  QUERY_STRING       $query_string;
          fastcgi_param  REQUEST_METHOD     $request_method;
          fastcgi_param  CONTENT_TYPE       $content_type;
          fastcgi_param  CONTENT_LENGTH     $content_length;
          fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
          fastcgi_param  REQUEST_URI        $request_uri;
          fastcgi_param  DOCUMENT_URI       $document_uri;
          fastcgi_param  DOCUMENT_ROOT      $document_root;
          fastcgi_param  SERVER_PROTOCOL    $server_protocol;
          fastcgi_param  REQUEST_SCHEME     $scheme;
          fastcgi_param  HTTPS              $https if_not_empty;
          fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
          fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;
          fastcgi_param  REMOTE_ADDR        $remote_addr;
          fastcgi_param  REMOTE_PORT        $remote_port;
          fastcgi_param  SERVER_ADDR        $server_addr;
          fastcgi_param  SERVER_PORT        $server_port;
          fastcgi_param  SERVER_NAME        $server_name;
    
          # PHP only, required if PHP was built with --enable-force-cgi-redirect
          fastcgi_param  REDIRECT_STATUS    200;
          fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
       }
      }
    
      # ----------------------------------------------------------------------
      # | SSL engine                                                         |
      # ----------------------------------------------------------------------
      ssl_session_timeout 24h;
      ssl_session_cache shared:SSL:10m;
      keepalive_timeout 300s;
      ssl_session_tickets off;
      ssl_prefer_server_ciphers on;
    
      # ----------------------------------------------------------------------
      # | Certificate files                                                  |
      # ----------------------------------------------------------------------
      ssl_certificate         /etc/letsencrypt/live/mydomain.com/fullchain.pem;
      ssl_certificate_key     /etc/letsencrypt/live/mydomain.com/privkey.pem;
      ssl_dhparam             /etc/letsencrypt/dhparam.pem;
    
      ssl_trusted_certificate /etc/letsencrypt/live/mydomain.com/chain.pem;
    
      # ----------------------------------------------------------------------
      # | SSL policy - Balanced                                              |
      # ----------------------------------------------------------------------
      ssl_protocols TLSv1.2 TLSv1.3;
      ssl_ciphers "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHAZO-POLY1305:ECDHE-ECDSA-AES256-SHA384";
    
      ssl_ecdh_curve secp521r1:secp384r1:prime256v1;
    
      # ----------------------------------------------------------------------
      # | Custom error messages/pages                                        |
      # ----------------------------------------------------------------------
      error_page 404 /404.html;
    
      # configuration file /etc/nginx/h5bp/basic.conf:
      include h5bp/security/referrer-policy.conf;
      include h5bp/security/x-content-type-options.conf;
      include h5bp/security/x-frame-options.conf;
      include h5bp/location/security_file_access.conf;
      include h5bp/cross-origin/requests.conf;
    
      # ----------------------------------------------------------------------
      # | Referrer Policy                                                    |
      # ----------------------------------------------------------------------
    
      # Set a strict Referrer Policy to mitigate information leakage.
    
      add_header Referrer-Policy $referrer_policy always;
    
      # ----------------------------------------------------------------------
      # | Content Type Options                                               |
      # ----------------------------------------------------------------------
    
      add_header X-Content-Type-Options nosniff always;
    
      # configuration file /etc/nginx/h5bp/security/x-frame-options.conf:
      # ----------------------------------------------------------------------
      # | Frame Options                                                      |
      # ----------------------------------------------------------------------
      add_header X-Frame-Options $x_frame_options always;
    
      # ----------------------------------------------------------------------
      # | File access                                                        |
      # ----------------------------------------------------------------------
    
      location ~* /\.(?!well-known\/) {
        deny all;
      }
    
      location ~* (?:#.*#|\.(?:bak|conf|dist|fla|in[ci]|log|orig|psd|sh|sql|sw[op])|~)$ {
        deny all;
      }
    
      # ----------------------------------------------------------------------
      # | Cross-origin requests                                              |
      # ----------------------------------------------------------------------
      add_header Access-Control-Allow-Origin $cors;
    
    
  6. 我的 php-fpm 配置如下所示 /etc/php/8.1/fpm/php-fpm.conf:>>

    ;;;;;;;;;;;;;;;;;;;;;
    ; FPM Configuration ;
    ;;;;;;;;;;;;;;;;;;;;;
    
    ;;;;;;;;;;;;;;;;;;
    ; Global Options ;
    ;;;;;;;;;;;;;;;;;;
    
    [global]
    pid = /var/run/php/php8.1-fpm.pid
    
    ; Error log file
    error_log = /var/log/php8.1-fpm.log
    
    ;;;;;;;;;;;;;;;;;;;;
    ; Pool Definitions ;
    ;;;;;;;;;;;;;;;;;;;;
    include=/etc/php/8.1/fpm/pool.d/*.conf
    

    /etc/php/8.1/fpm/php.ini >>

    ;;;;;;;;;;;;;;;;;;;;
    ; Language Options ;
    ;;;;;;;;;;;;;;;;;;;;
    engine = On
    short_open_tag = Off
    precision = 14
    output_buffering = 4096
    zlib.output_compression = Off
    implicit_flush = Off
    unserialize_callback_func =
    serialize_precision = -1
    disable_functions =
    disable_classes =
    zend.enable_gc = On
    zend.exception_ignore_args = On
    zend.exception_string_param_max_len = 0
    
    ;;;;;;;;;;;;;;;;;
    ; Miscellaneous ;
    ;;;;;;;;;;;;;;;;;
    expose_php = Off
    
    ;;;;;;;;;;;;;;;;;;;
    ; Resource Limits ;
    ;;;;;;;;;;;;;;;;;;;
    max_execution_time = 30
    max_input_time = 60
    memory_limit = 128M
    
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ; Error handling and logging ;
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
    display_errors = Off
    display_startup_errors = Off
    log_errors = On
    ignore_repeated_errors = Off
    ignore_repeated_source = Off
    report_memleaks = On
    
    ;;;;;;;;;;;;;;;;;
    ; Data Handling ;
    ;;;;;;;;;;;;;;;;;
    variables_order = "GPCS"
    request_order = "GP"
    register_argc_argv = Off
    auto_globals_jit = On
    post_max_size = 8M
    auto_prepend_file =
    auto_append_file =
    default_mimetype = "text/html"
    default_charset = "UTF-8"
    
    ;;;;;;;;;;;;;;;;;;;;;;;;;
    ; Paths and Directories ;
    ;;;;;;;;;;;;;;;;;;;;;;;;;
    doc_root =
    user_dir =
    enable_dl = Off
    cgi.force_redirect = 1
    fastcgi.logging = 1
    
    ;;;;;;;;;;;;;;;;
    ; File Uploads ;
    ;;;;;;;;;;;;;;;;
    file_uploads = Off
    upload_max_filesize = 2M
    max_file_uploads = 20
    
    ;;;;;;;;;;;;;;;;;;
    ; Fopen wrappers ;
    ;;;;;;;;;;;;;;;;;;
    allow_url_fopen = On
    allow_url_include = Off
    
    ;;;;;;;;;;;;;;;;;;;
    ; Module Settings ;
    ;;;;;;;;;;;;;;;;;;;
    cli_server.color = On
    
    pdo_mysql.default_socket=
    
    SMTP = localhost
    smtp_port = 25
    
    odbc.allow_persistent = On
    odbc.check_persistent = On
    odbc.max_persistent = -1
    odbc.max_links = -1
    odbc.defaultlrl = 4096
    odbc.defaultbinmode = 1
    
    mysqli.max_persistent = -1
    mysqli.allow_persistent = On
    mysqli.max_links = -1
    mysqli.default_port = 3306
    mysqli.default_socket =
    mysqli.default_host =
    mysqli.default_user =
    mysqli.default_pw =
    mysqli.reconnect = Off
    mysqlnd.collect_statistics = On
    mysqlnd.collect_memory_statistics = Off
    
    pgsql.allow_persistent = On
    pgsql.auto_reset_persistent = Off
    pgsql.max_persistent = -1
    pgsql.max_links = -1
    pgsql.ignore_notice = 0
    pgsql.log_notice = 0
    bcmath.scale = 0
    
    session.save_handler = files
    session.use_strict_mode = 0
    session.use_cookies = 1
    session.use_only_cookies = 1
    session.name = PHPSESSID
    session.auto_start = 0
    session.cookie_lifetime = 0
    session.cookie_path = /
    session.cookie_domain =
    session.cookie_httponly =
    session.cookie_samesite =
    session.serialize_handler = php
    session.gc_probability = 0
    session.gc_divisor = 1000
    session.gc_maxlifetime = 1440
    session.referer_check =
    session.cache_limiter = nocache
    session.cache_expire = 180
    session.use_trans_sid = 0
    session.sid_length = 26
    session.trans_sid_tags = "a=href,area=href,frame=src,form="
    session.sid_bits_per_character = 5
    
    [Assertion]
    zend.assertions = -1
    
    [Tidy]
    tidy.clean_output = Off
    
    [soap]
    ; Enables or disables WSDL caching feature.
    soap.wsdl_cache_enabled=1
    soap.wsdl_cache_dir="/tmp"
    soap.wsdl_cache_ttl=86400
    soap.wsdl_cache_limit = 5
    
    [ldap]
    ldap.max_links = -1
    

    /etc/php/8.1/fpm/pool.d/www.conf >>

    
    
     ; Start a new pool named 'www'.
     [www]
    
     ; Unix user/group of processes
     user = www-data
     group = www-data
    
     ; The address on which to accept FastCGI requests.
     listen = /var/run/php8.1-fpm.sock
    
     ; Set permissions for unix socket, if one is used. In Linux, read/write
     ; permissions must be set in order to allow connections from a web server. Many
     ; BSD-derived systems allow connections regardless of permissions. The owner
     ; and group can be specified either by name or by their numeric IDs.
     listen.owner = www-data
     listen.group = www-data
     listen.mode = 0660
    
     ; Choose how the process manager will control the number of child processes.
     pm = dynamic
    
     ; The number of child processes to be created when pm is set to 'static' and the
     ; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
     pm.max_children = 5
    
     ; The number of child processes created on startup.
     pm.start_servers = 2
    
     ; The desired minimum number of idle server processes.
     pm.min_spare_servers = 1
    
     ; The desired maximum number of idle server processes.
     pm.max_spare_servers = 3
    
     ; Chroot to this directory at the start. This value must be defined as an
     chroot = /var/www/the-ts.com
    
     ; Chdir to this directory at the start.
     chdir = /
    

/var/log/nginx/access.log 或 /var/log/nginx/error.log 以及 /var/log/php-fpm.log 中没有值得注意的错误

nginx 和 php-fpm 的所有 systemctl 状态查询看起来都很好。

ufw 已启用,并且已允许“OpenSSH”和“Nginx Full”端口。

答案1

我无法确定上述配置存在什么问题。相反,我会与遇到同样问题的人分享我的工作配置。

# configuration file /etc/nginx/nginx.conf:
user                                          www-data;
pid                                           /run/nginx.pid;
worker_processes                              auto;
worker_rlimit_nofile                          65535;

# Load modules
include                                       /etc/nginx/modules-enabled/*.conf;

events {
    multi_accept                              on;
    worker_connections                        65535;
}

http {
    sendfile                                  on;
    tcp_nopush                                on;
    tcp_nodelay                               on;
    server_tokens                             off;
    log_not_found                             off;
    client_max_body_size                      16M;

    # MIME
    include                                   mime.types;
    default_type                              application/octet-stream;

   # Set character encodings.
    charset utf-8;
    charset_types
      text/css
      text/plain
      text/vnd.wap.wml
      text/javascript
      text/markdown
      text/calendar
      text/x-component
      text/vcard
      text/cache-manifest
      text/vtt
      application/json
      application/manifest+json;

    # Log Format
    log_format                                cloudflare '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $http_cf_ray $http_cf_connecting_ip $http_x_forwarded_for $http_x_forwarded_proto $http_true_client_ip $http_cf_ipcountry $http_cf_visitor';

    # Logging
    #access_log                                /var/log/nginx/access.log cloudflare;
    #error_log                                 /var/log/nginx/error.log warn;

    # Cacheing
    open_file_cache                           max=1000 inactive=20s;
    open_file_cache_valid                     30s;
    open_file_cache_min_uses                  2;
    open_file_cache_errors                    on;

    # Specify file cache expiration.
    map $sent_http_content_type $expires {
      default                                 1y;

      # No content
      ""                                      off;

      # CSS
      ~*text/css                              1y;

      # Data interchange
      ~*application/atom\+xml                 1h;
      ~*application/rdf\+xml                  1h;
      ~*application/rss\+xml                  1h;

      ~*application/json                      0;
      ~*application/ld\+json                  0;
      ~*application/schema\+json              0;
      ~*application/geo\+json                 0;
      ~*application/xml                       0;
      ~*text/calendar                         0;
      ~*text/xml                              0;

      # Favicon (cannot be renamed!) and cursor images
      ~*image/vnd.microsoft.icon              1w;
      ~*image/x-icon                          1w;

      # HTML
      ~*text/html                             0;

      # JavaScript
      ~*application/javascript                1y;
      ~*application/x-javascript              1y;
      ~*text/javascript                       1y;

      # Manifest files
      ~*application/manifest\+json            1w;
      ~*application/x-web-app-manifest\+json  0;
      ~*text/cache-manifest                   0;

      # Markdown
      ~*text/markdown                         0;

      # Media files
      ~*audio/                                1y;
      ~*image/                                1y;
      ~*video/                                1y;

      # WebAssembly
      ~*application/wasm                      1y;

      # Web fonts
      ~*font/                                 1y;
      ~*application/vnd.ms-fontobject         1y;
      ~*application/x-font-ttf                1y;
      ~*application/x-font-woff               1y;
      ~*application/font-woff                 1y;
      ~*application/font-woff2                1y;

      # Other
      ~*text/x-cross-domain-policy            1w;
    }
    expires $expires;


    # Add X-Frame-Options for HTML documents.
    map $sent_http_content_type $x_frame_options {
        ~*text/html DENY;
    }

    # Add Content-Security-Policy for HTML documents.
    map $sent_http_content_type $content_security_policy {
        ~*text/(html|javascript)|application/pdf|xml "default-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; object-src 'none'; upgrade-insecure-requests";
    }

    # Add Permissions-Policy for HTML documents.
    map $sent_http_content_type $permissions_policy {
        ~*text/(html|javascript)|application/pdf|xml "accelerometer=(),autoplay=(),camera=(),display-capture=(),document-domain=(),encrypted-media=(),fullscreen=(),geolocation=(),gyroscope=(),magnetometer=(),microphone=(),midi=(),payment=(),picture-in-picture=(),publickey-credentials-get=(),screen-wake-lock=(),sync-xhr=(self),usb=(),web-share=(),xr-spatial-tracking=()";
    }

    # Add Referrer-Policy for HTML documents.
    map $sent_http_content_type $referrer_policy {
        ~*text/(css|html|javascript)|application\/pdf|xml "strict-origin-when-cross-origin";
    }

    # Add Cross-Origin-Policies for HTML documents.
    # Cross-Origin-Embedder-Policy
    map $sent_http_content_type $coep_policy {
        ~*text/(html|javascript)|application/pdf|xml "require-corp";
    }

    # Cross-Origin-Opener-Policy
    map $sent_http_content_type $coop_policy {
        ~*text/(html|javascript)|application/pdf|xml "same-origin";
    }

    # Cross-Origin-Resource-Policy
    map $sent_http_content_type $corp_policy {
        ~*text/(html|javascript)|application/pdf|xml "same-origin";
    }

    # Add Access-Control-Allow-Origin.
    map $sent_http_content_type $cors {
        # Images
        ~*image/ "*";

        # Web fonts
        ~*font/                         "*";
        ~*application/vnd.ms-fontobject "*";
        ~*application/x-font-ttf        "*";
        ~*application/font-woff         "*";
        ~*application/x-font-woff       "*";
        ~*application/font-woff2        "*";
    }


    # Load configs
    include                                  /etc/nginx/conf.d/*.conf;

    # MyDoMain.de
    server {
        listen                               MyIP:443 ssl http2;
        listen                               [MyIPv6]:443 ssl http2;

        server_name                          www.MyDoMain.de;

        set                                  $base /var/www/MyDoMain.de;
        root                                 $base/public;

        # SSL
        include                              ssl.conf;

        # restrict methods
        if ($request_method !~ ^(GET|POST|HEAD)$) {
            return '405';
        }

        # logging
        access_log /var/www/log/nginx.access.log cloudflare;
        error_log  /var/www/log/nginx.error.log warn;

        # index.php
        index      index.php;

        # index.html fallback
        location / {
            try_files $uri $uri/ /index.html;
            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                # Custom headers and headers various browsers *should* be OK with but aren't
                add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                # Tell client that this pre-flight info is valid for 20 days
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain; charset=utf-8';
                add_header 'Content-Length' 0;
                return 204;
            }
            if ($request_method = 'POST') {
                add_header 'Access-Control-Allow-Origin' '*' always;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
                add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
                add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
            }
            if ($request_method = 'GET') {
                add_header 'Access-Control-Allow-Origin' '*' always;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
                add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
                add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
            }
        }

        # index.php fallback
        location ~ ^/var/www/MyDoMain.de/ {
            try_files $uri $uri/ /index.php?$query_string;
        }

        # favicon.ico
        location = /favicon.ico {
            log_not_found off;
            access_log    off;
        }

        # robots.txt
        location = /robots.txt {
            log_not_found off;
            access_log    off;
        }

        # assets, media
        location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
            expires    7d;
            access_log off;
        }

        # svg, fonts
        location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
            add_header Access-Control-Allow-Origin "*";
            expires    7d;
            access_log off;
        }

        # handle .php
        location ~ \.php$ {
            fastcgi_pass                    unix:/var/run/php/php-fpm.sock;

            # 404
            try_files                       $fastcgi_script_name =404;

            # default fastcgi_params
            include                         fastcgi.conf;

            # fastcgi settings
            fastcgi_index                   index.php;
            fastcgi_buffers                 8 16k;
            fastcgi_buffer_size             32k;
        }

        # Referrer Policy
        add_header Referrer-Policy $referrer_policy always;

        # X-Content-Type-Options
        add_header X-Content-Type-Options nosniff always;

        # X-Frame-Options
        add_header X-Frame-Options $x_frame_options always;

        # Security-File-Access
        location ~* /\.(?!well-known\/) {
          deny all;
        }

        location ~* (?:#.*#|\.(?:bak|conf|dist|fla|in[ci]|log|orig|psd|sh|sql|sw[op])|~)$ {
          deny all;
        }

        # Cross-Origin-Requests
        add_header Access-Control-Allow-Origin $cors;

    }

    # non-www, subdomains redirect, ssl
    server {
        listen                              MyIP:443 ssl http2;
        listen                              [MyIPv6]:443 ssl http2;

        server_name                         .MyDoMain.de;

        # SSL
        include                             ssl.conf;

        # redirect
        return                              301 https://www.MyDoMain.de$request_uri;
    }

    # HTTP redirect
    server {
        listen                              MyIP:80;
        listen                              [MyIPv6]:80;

        server_name                         www.MyDoMain.de MyDoMain.de;

        # redirect
        location / {
            return 301                      https://www.MyDoMain.de$request_uri;
        }
    }
}

# configuration file /etc/nginx/modules-enabled/50-mod-http-auth-pam.conf:
load_module modules/ngx_http_auth_pam_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-cache-purge.conf:
load_module modules/ngx_http_cache_purge_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-dav-ext.conf:
load_module modules/ngx_http_dav_ext_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-echo.conf:
load_module modules/ngx_http_echo_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-fancyindex.conf:
load_module modules/ngx_http_fancyindex_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-geoip.conf:
load_module modules/ngx_http_geoip_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-geoip2.conf:
load_module modules/ngx_http_geoip2_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-headers-more-filter.conf:
load_module modules/ngx_http_headers_more_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-image-filter.conf:
load_module modules/ngx_http_image_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-perl.conf:
load_module modules/ngx_http_perl_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-subs-filter.conf:
load_module modules/ngx_http_subs_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-uploadprogress.conf:
load_module modules/ngx_http_uploadprogress_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-upstream-fair.conf:
load_module modules/ngx_http_upstream_fair_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-xslt-filter.conf:
load_module modules/ngx_http_xslt_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-mail.conf:
load_module modules/ngx_mail_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-nchan.conf:
load_module modules/ngx_nchan_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-stream.conf:
load_module modules/ngx_stream_module.so;

# configuration file /etc/nginx/modules-enabled/70-mod-stream-geoip.conf:
load_module modules/ngx_stream_geoip_module.so;

# configuration file /etc/nginx/modules-enabled/70-mod-stream-geoip2.conf:
load_module modules/ngx_stream_geoip2_module.so;

# configuration file /etc/nginx/mime.types:

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

# configuration file /etc/nginx/ssl.conf:
# SSL
ssl_session_timeout             1d;
ssl_session_cache               shared:SSL:10m;
ssl_session_tickets             off;

ssl_protocols                   TLSv1.2 TLSv1.3;
ssl_ciphers                     "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHAZO-POLY1305:ECDHE-ECDSA-AES256-SHA384";
ssl_ecdh_curve                  secp521r1:secp384r1:prime256v1;
ssl_prefer_server_ciphers       on;

# Create session ticket key:    openssl rand -out /etc/nginx/ssl/session_ticket_key 48
ssl_session_ticket_key          /etc/nginx/ssl/session_ticket_key;

# Create dhparam4096.pem:       openssl dhparam -out /etc/nginx/ssl/dhparam4096.pem 4096
ssl_dhparam                     /etc/nginx/ssl/dhparam.pem;

# OCSP Stapling
ssl_stapling                    on;
ssl_stapling_verify             on;
resolver                        1.1.1.1 1.0.0.1 [2606:4700:4700::1111] [2606:4700:4700::1001] 208.67.222.222 208.67.220.220 [2620:119:35::35] [2620:119:53::53] valid=60s;
resolver_timeout                2s;

# set certificate files
ssl_certificate                 /etc/letsencrypt/live/MyDoMain.de/fullchain.pem;
ssl_certificate_key             /etc/letsencrypt/live/MyDoMain.de/privkey.pem;
ssl_trusted_certificate         /etc/letsencrypt/live/MyDoMain.de/chain.pem;

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

# configuration file /etc/nginx/fastcgi.conf:

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  REMOTE_USER        $remote_user;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

答案2

所以你有了:

  • 拥有自己 IP 的 VPS 服务器
  • 一个 CloudFlare 帐户,其中 YourDomain.com 指向 Cloudflare IP。

启动 VPS 后,将其 IP 放入 cloudflare 作为后端该域名。

当我查找 YourDomain.com 时,我会获得 cloudflare IP,而当我将 Web 浏览器指向 YourDomain.com 时,它会连接到 cloudflare,然后将该请求转发到您的 VPS。

只需运行 nginx 就足以看到基本的“YourDomain.com/index.html”。

相关内容