Маршрутизация в подкаталог как новый маршрут с nGinx

Вот мой текущий серверный блок (ниже). У меня есть отдельный блог wordpress, установленный в / blog, и мне нужно направить / blog в каталог "/home/forge/example.com/public/blog".

. Я пробовал несколько вариантов и не могу найти совет с благодарностью получен.

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/example.com/before/*;

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;
    root /home/forge/example.com/public;

# FORGE SSL (DO NOT REMOVE!)
ssl_certificate /etc/nginx/ssl/example.com/server.crt;
ssl_certificate_key 
/etc/nginx/ssl/example.com/server.key;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'REMOVED FOR DEMO';
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/nginx/dhparams.pem;

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";

index index.html index.htm index.php;

charset utf-8;

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/example.com/server/*;


location / {
    try_files $uri $uri/ /index.php?$query_string;
}

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

access_log off;
error_log  /var/log/nginx/example.com-error.log error;

error_page 404 /index.php;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

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

}

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/example.com/after/*;

Вот что я пробовал добавить:

location /blog/ {
    root /home/forge/example.com/public/blog;
    try_files $uri $uri/ /index.php?$query_string;
}

# the images need a seperate entry as we dont want to concatenate that with index.php      
location ~ /blog/.+\.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
    root /home/forge/example.com/public/blog;
}
# pass the PHP scripts to FastCGI server
location ~ /blog/.+\.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    allow 127.0.0.1;
    # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_index index.php;
}
1
задан 2 October 2017 в 15:06
1 ответ

Вот фрагмент, который, вероятно, сработает (у меня нет Forge, чтобы его проверить) ...

location /blog {
  try_files $uri $uri/ /blog/index.php$args$query_string;
  location ~ .+\.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_index index.php;
  }
}

# the following location is not needed - so commented out.
# location ^~ /blog/.+\.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
    # expires max;
# }

Возвращаясь к тому, почему ваша конфигурация не сработала ...

Когда вы упоминаете что-то вроде этого ...

location /blog {
  root /home/forge/example.com/public/blog;
  # ... other configuration lines
}

Nginx будет искать "index.php" в папке с именем "/home/forge/example.com/public/blog/blog", что приведет к ошибке ( 404 или 403, если он пуст - попробуйте создать такую ​​папку и попробуйте создать файл index.php с в нем). Я вложил блоки PHP. Их можно разместить без вложений, вот так ...

location /blog {
    try_files $uri $uri/ /index.php$args$query_string;
}

# pass the PHP scripts to FastCGI server
location ^~ /blog/.+\.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    allow 127.0.0.1;
    # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_index index.php;
}

Обратите внимание на изменение модификатора ^ ~ во втором блоке расположения. Без него блок местоположения PHP основного сайта (Laravel) может иметь приоритет, что приведет к нежелательным результатам. Дополнительная информация о том, как работает блок местоположения и порядок приоритета, доступна в официальных документах .

Для установки в подкаталоге статические файлы должны работать правильно без необходимости в отдельном блоке местоположения.

0
ответ дан 4 December 2019 в 04:34

Теги

Похожие вопросы