Назад | Перейти на главную страницу

Как изменить порядок загрузки домена и имени поддомена на nginx?

Я включил Wordpress Multisite с подкаталогом на сервере VPS nginx. У меня также работает roundcube и postfix. URL-адрес для доступа к почте - webmail.mysite.com. Проблема в том, что webmail.mysite.com перенаправляется на mysite.com, что ожидается. Я выяснил, что это из-за упорядочивания доменов и поддоменов. Руководство по wordpress https://codex.wordpress.org/Configuring_Wildcard_Subdomains_for_multi_site_under_Plesk_Control_Panel написан для сервера apache. Как я могу назначить первый приоритет субдомену на сервере nginx.

Nginx.conf

user www-data;
worker_processes auto;
worker_rlimit_nofile 100000;
pid /run/nginx.pid;

events {
        worker_connections 4096;
        multi_accept on;
}

http {
        ##
        ##
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 30;
    types_hash_max_size 2048;

    server_tokens off;
    reset_timedout_connection on;
    add_header X-Powered-By "EasyEngine 3.3.15";
    add_header rt-Fastcgi-Cache $upstream_cache_status;

    # Limit Request
    limit_req_status 403;
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    # Proxy Settings
    # set_real_ip_from      proxy-server-ip;
    # real_ip_header        X-Forwarded-For;

    fastcgi_read_timeout 300;
    client_max_body_size 100m;

    ##
    # SSL Settings
    ##
        ssl_session_timeout 10m;
        ssl_prefer_server_ciphers on;
        ssl_ciphers HIGH:!aNULL:!MD5:!kEDH;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ##
    # Basic Settings
    ##
    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Log format Settings
    log_format rt_cache '$remote_addr $upstream_response_time $upstream_cache_status [$time_local] '
    '$http_host "$request" $status $body_bytes_sent '
    '"$http_referer" "$http_user_agent"';

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types
        application/atom+xml
        application/javascript
        application/json
            application/rss+xml
            application/vnd.ms-fontobject
            application/x-font-ttf
            application/x-web-app-manifest+json
            application/xhtml+xml
            application/xml
            font/opentype
            image/svg+xml
            image/x-icon
            text/css
            text/plain
            text/x-component
            text/xml
            text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

Изменить У меня есть три файла в каталоге с поддержкой сайтов (1) дефолт

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        # include snippets/snakeoil.conf;
        #
        # ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # don’t use SSLv3 ref: POODLE
        # ssl_ciphers HIGH:!aNULL:!MD5;
        # ssl_prefer_server_ciphers on;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php5-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php5-fpm:
        #       fastcgi_pass unix:/var/run/php5-fpm.sock;
        #}

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


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}
  1. udcc.in

    server {
    
        # Uncomment the following line for domain mapping
        # listen 80 default_server;
    
        server_name udcc.in   *.udcc.in;
    
        # Uncomment the following line for domain mapping
        #server_name_in_redirect off;
    
        access_log /var/log/nginx/udcc.in.access.log rt_cache;
        error_log /var/log/nginx/udcc.in.error.log;
    
    
        root /var/www/udcc.in/htdocs;
    
    
    
       index index.php index.html index.htm;
    
    
       include common/php.conf;
       include common/wpsubdir.conf;
       include common/wpcommon.conf;
       include common/locations.conf;
       include /var/www/udcc.in/conf/nginx/*.conf;
    }
    
  2. электронная почта

    server {
    
       server_name   webmail.* ;
    
       access_log /var/log/nginx/webmail.access.log rt_cache;
       error_log /var/log/nginx/webmail.error.log;
    
       root /var/www/roundcubemail/htdocs/;
    
       index index.php index.html index.htm;
    
       include common/php.conf;
    
       include common/locations.conf;
    
    }
    

location.conf

# NGINX CONFIGURATION FOR COMMON LOCATION
# Basic locations files
location = /favicon.ico {
  access_log off;
  log_not_found off;
  expires max;
}
location = /robots.txt {
  # Some WordPress plugin gererate robots.txt file
  # Refer #340 issue
  try_files $uri $uri/ /index.php?$args;
  access_log off;
  log_not_found off;
}
# Cache static files
location ~* \.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|swf)$ {
  add_header "Access-Control-Allow-Origin" "*";
  access_log off;
  log_not_found off;
  expires max;
}
# Security settings for better privacy
# Deny hidden files
location ~ /\. {
  deny all;
  access_log off;
  log_not_found off;
}
# Deny backup extensions & log files
location ~* ^.+\.(bak|log|old|orig|original|php#|php~|php_bak|save|swo|swp|sql)$ {
  deny all;
  access_log off;
  log_not_found off;
}
# Return 403 forbidden for readme.(txt|html) or license.(txt|html) or example.(txt|html)
if ($uri ~* "^.+(readme|license|example)\.(txt|html)$") {
  return 403;
}
# Status pages
location /nginx_status {
  stub_status on;
  access_log off;
  include common/acl.conf;
}
location ~ ^/(status|ping) {
  include fastcgi_params;
  fastcgi_pass php;
  include common/acl.conf;
}

Есть 2 варианта предоставить виртуальный хост (server {} block) более высокий приоритет в Nginx:

  1. Поместите это выше других. Обычно виртуальные хосты сохраняются в разных файлах, например site.com.conf и site2.com.conf, в этом случае добавьте перфикс для установки порядка, например: 00-site.com.conf, 01-site.com.conf

  2. Добавить default_server к listen директива (в вашем случае для виртуального хоста с несколькими сайтами). Это сделает его виртуальным хостом по умолчанию для данной комбинации IP (если установлено) - порт.