Nginx доступ к моему сайту с субдомена скачивает файл - PullRequest
0 голосов
/ 10 апреля 2020

При настройке моего сайта с использованием Nginx и следуя некоторым инструкциям из статьи, мне удалось заставить работать основной домен. (набрав example.com). На моем веб-сайте также имеется поддомен (forum.example.com), который вместо запуска веб-страницы форума загружает основной файл php, вместо которого выполняется, как только запрос отправляется на мой сервер.

Эта проблема также возникает, когда я набираю www.forum.example.com, но не при включении префикса https: // для www.forum.example.com и forum.example.com.

Я не совсем уверен, почему exampe.com запрос работает, а forum.example.com - нет. Я что-то пропускаю?

Я использую certbot (давайте зашифруем), чтобы включить безопасное соединение. Ниже я перечисляю блоки серверов из каталога с поддержкой сайта:

example.com

server {

        if ($host = example.com) {
                return 301 https://www.example.com$request_uri;
        } # managed by Certbot

        server_name www.example.com example.com www.forum.example.com forum.example.com;
        root /var/www/example/public;

        index index.php index.html index.htm;
        location / {
                try_files $uri $uri/ /index.php?$uri&$args;
        }

        listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot
        listen 443 ssl http2; # managed by Certbot

        index index.php index.html index.htm;

        location ~ \.php$ {
                try_files $uri /index.php?q=$uri&$args =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

                # With php5-cgi alone:
                #fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        }

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
        if ($host = www.example.com) {
                return 301 https://www.example.com$request_uri;
        } # managed by Certbot

        if ($host = example.com) {
                return 301 https://www.example.com$request_uri;
        } # managed by Certbot

#        listen 80 default_server;

        server_name localhost;
        return 404; # managed by Certbot
}

И файл по умолчанию:

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        #root /var/www/html;
        root /var/www/example/public;

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

        server_name example.com www.example.com;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
                # proxy_pass http://localhost:8080;
                # proxy_http_version 1.1;
                # proxy_set_header Upgrade $http_upgrade;
                # proxy_set_header Connection 'upgrade';
                # proxy_set_header Host $host;
                # proxy_cache_bypass $http_upgrade;
        }

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

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




}

Вещи, которые я пытался включить :

  • изменение порядка значений имени_сервера, поэтому начните с forum.example.com вместо example.com. В первом блоке сервера добавляем дополнительный оператор if в начале: if ($ host = forum.example.com) {return 301 https://forum.example.com $ request_uri; } # управляется Certbot

Еще одна проблема, с которой я столкнулся, была из любой статьи, которую я посещал, они просто сказали вам вставить код, не объясняя, что делает каждый блок метода / кода, поэтому я не стал на самом деле не получают базового c понимания того, что происходит. Если у кого-то есть дополнительное время, чтобы объяснить и помочь мне понять, как обрабатываются запросы и почему возникает эта ошибка, было бы гораздо более полезным.

Sidenode : веб-сайт размещается на VPS-сервере, и когда я пытаюсь отправить запрос с компьютера, который я использую прямо сейчас (example.com), я вижу следующее от Chrome, Firefox и Safari, но когда я получаю доступ к example.com с других моих устройств (iphone, других ноутбуков / компьютеров) я могу получить доступ к своему веб-сайту. При этом предполагается, что все данные и кеш очищаются с моего компьютера каждый раз, когда я пытаюсь получить доступ к своему веб-сайту и из режима инкогнито.

Пожалуйста, дайте мне знать, если мне потребуется дополнительная информация.

Помощь будет высоко ценится!

...