Не работает mod rewrite nginx

Nginx не работает rewrite

Есть один сайт, на nginx + php-fpm. Нужно сделать rewrite, чтобы обращения на saet.ru/uploads/123.jpg переписывались в saet.ru/saet/image/?image=/uploads/123.jpg.

Добавил блок location /uploads в конфиге ниже. Но вместо нужной станички отдается 404 ошибка.

Пробовал rewrite помещать выще в саму секцию server с параметром last, но все равно та же самая ошибка.

Функция rewrite есть в апаче а не нжинксе. Покажи лог ошибок нжинкса

А почему у тебя не по сокетам работа настроена ?
https://www.nginx.com/blog/creating-nginx-rewrite-rules/
ищи по «Example – Configuring Custom Rerouting»

Функция rewrite есть в апаче а не нжинксе

А почему у тебя не по сокетам работа настроена ?

Досталось по наследству, потом будет исправлено.

ищи по «Example – Configuring Custom Rerouting»

Ну у меня это и делается по сути, но почему-то не работает.

— каталог /saet/image существует?

^/uploads/(.*)$
Если не рбаотает — курить лог.

Нет, этот путь обрабатывается в php-скрипте.

Но все это не важно, т.к. оказалась проблема в том, что php-скрипту передается оригинальный request_uri, а не измененный.

Пока накостылял такое решение:

Сама регулярка работает правильно, но почемуто измененный uri не передается в php-скрипт.

В требовании написано, что нужно получить «saet.ru/saet/image/?image=123.jpg», а регулярка из конфига, насколько я вижу, отдаст «saet.ru/saet/image/?image=/uploads/123.jpg».

Нужен именно 2 вариант, поправил оп пост.

break заменить на last в location /uploads/
Убрать try_files из location /uploads/ т.к «last завершает обработку текущего набора директив модуля ngx_http_rewrite_module, после чего ищется новый location, соответствующий изменённому URI»
Т.е попадет в location / и далее в location

\.php$ а в php приходит env /saet/image/?image=/uploads/123.jpg

Так я тоже делал. Результат тот же самый. Но я нашел еще один костыльный способ, помимо того, что выше.

Источник

Nginx Rewrite не работает, как решить?

Здравствуйте. Имеется скрипт на php в корне лежит файл .htaccess и в папке /router лежит файл .htaccess

Тот что лежит в корне:

Тот что в директории /router:

Конфиг nginx default:

Пробовал различные онлайн конвертеры, ничего не помогло. Подскажите, что делаю не так?

  • Вопрос задан более трёх лет назад
  • 851 просмотр

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

Эквивалент вашим .htaccess, будет выглядеть как-то так:

Ну и нужен вам, вероятно, не default конфиг nginx править, а создать конфиг для вашего домена отдельный. А default пусть заглушкой отвечает, при не попадании в домен, как это по умолчанию и сделано.

rewrite работает с той же строкой что и location.
/ не совпадает с шаблоном ^$ .

При использовании break не происходит поиска location соответствующего изменённому URI и запрос уже не попадёт в location /router
nginx.org/ru/docs/http/ngx_http_rewrite_module.htm.

Вместо трёх location хватит одного:

Согласен, я немного поторопился. А break пролез из копипеста.

Источник

Enabling Nginx mod_rewrite

I just moved a WordPress blog on a new droplet hosting account. Previously the hosting was on Apache, now is on Nginx. I have a problem that now WordPress pretty links (post-name) are not working and I think the problem comes from the fact that mod)rewrite is not enabled.

Till now I had it in htaccess like

RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ — [L]
RewriteCond %FILENAME> !-f
RewriteCond %FILENAME> !-d
RewriteRule . /index.php [L]

How can I implement this in Nginx and where specifically? I am a complete beginner.

Join 1M+ other developers and:

  • Get help and share knowledge in Q&A
  • Subscribe to topics of interest
  • Get courses & tools that help you grow as a developer or small business owner

Join Now

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Nginx does not support .htaccess files.

On CentOS Nginx stores virtual host files in /etc/nginx/conf.d. I assume you’re using the default.conf file. So edit this file and find the following:

and make the following change:

Save the file and reload Nginx:

I can’t find default.conf file with the location /etc/nginx/conf.d.

Should I need to copy-paste above file code and create new file with that location?

In your site’s server block add /index.php?$args;
to try_files so that you get something like this:

try_files $uri $uri/ /index.php?$args;

Then go into your WordPress settings and re-enable pretty permalinks.

What is the server block and how/where can I access it? I am really a beginner.

^^ you can find it in the path
/etc/nginx/sites-avaliable/yoursite.com

This was exactly what I needed, thank you.

I have the following:

Should I just replace the above line with

Or should I add it as a new line? Just curious about that before I commit to the change.

Thank you
Brian

This worked for me 🙂 My issue was that laravel 5.0 apparently creates URL’s differently than newer versions. This was resulting in constant 404’s despite, php artisan route:list returning all routes with no errors. Update the location block for / in the nginx.conf for the site from

My WORKED solution.
Already its mentioned by “UKn0Me March 7, 2015”

  1. Use filezilla, login to your SSH-FTP using top level SSH user (may ‘root’)
  2. Goto the path “/home/Domain-UserName/conf/web/nginx.conf”
  3. Probably you should see..

try_files $uri $uri/ /index.php?$args;
Here, Nginx checks for the existence of a file at the URL ($uri), then for a directory ($uri/).
If it doesn’t find a directory or a file, it performs an internal redirect to /index.php passing the query string arguments as parameters.

location / <
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$args;
>

  1. If your blog is in a subfolder (say /wordpress), you’ll have to add an extra location /wordpress/ block to your configuration file :

location /wordpress/ <
try_files $uri $uri/ /wordpress/index.php?$args;
>

Restart NGINX (or) may be whole server.

My server configs are:
DigitalOcean, Ubuntu 14x, Vesta Nginx+php-fpm, WordPress on subfolder.

Источник

Не работает mod rewrite nginx

Ребят, работал ранее с nginx-ом, всё втыкалось на ура, сейчас переехал на новый серв (debian) установил связку nginx + php+fpm.. перенес скрипты и удивился..

Rewrite на отрез отказывается работать.
Прообовал связки типа: rewrite ^/none.txt$ /index.php;
И ничего.. такое ощущение, что NginxHttpRewriteModule не заинстален..

Можете подсказать, где проверить наличие модуля, и как его подключить?

Ответить | Правка | Cообщить модератору

Оглавление

  • nginx — Не работает rewrite, hijacker, 19:04 , 01-Июн-12, (1)
    • nginx — Не работает rewrite, hijacker, 22:25 , 01-Июн-12, (2)

Сообщения по теме [Сортировка по времени | RSS]

2012/06/01 19:03:06 [error] 12311#0: *138 open() «/var/www/none.txt» failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: «GET /none.txt HTTP/1.1»

1. «nginx — Не работает rewrite» + / –
Сообщение от hijacker on 01-Июн-12, 19:04
Ответить | Правка | ^ к родителю #0 | Наверх | Cообщить модератору

2. «nginx — Не работает rewrite» + / –
Сообщение от hijacker on 01-Июн-12, 22:25

Решилось переустановкой nginx-а с офф репозитория

Источник

Не работает mod rewrite nginx

Потратил минут 20, пока нашел, почему не работает модуль apache mod_rewrite в Ubuntu 16.04

проверьте в конфигурационном файле /etc/apache2/apache.conf значение директивы AllowOverride

нужно

Options Indexes FollowSymLinks
AllowOverride All
Require all granted

было

Options Indexes FollowSymLinks
AllowOverride None
Require all granted

Предварительно (или потом) нужно включить модуль mod_rewrite командой:

sudo a2enmod rewrite

Проверить подключенные модули можно командой apachectl -M , должно быть что похожее:

core_module (static)
so_module (static)
watchdog_module (static)
http_module (static)
log_config_module (static)
logio_module (static)
version_module (static)
unixd_module (static)
access_compat_module (shared)
alias_module (shared)
auth_basic_module (shared)
authn_core_module (shared)
authn_file_module (shared)
authz_core_module (shared)
authz_host_module (shared)
authz_user_module (shared)
autoindex_module (shared)
deflate_module (shared)
dir_module (shared)
env_module (shared)
filter_module (shared)
mime_module (shared)
mpm_prefork_module (shared)
negotiation_module (shared)
php7_module (shared)
rewrite_module (shared)
setenvif_module (shared)
status_module (shared)

И перезапустить apache:

sudo systemctl restart apache2

Теперь можно настроить перенаправление в файле .htaccess :

Источник

Читайте также:  Не работает сигнализация ford
Оцените статью