nginx Compatibility
Делаем WordPress дружелюбнее к nginx
Описание Плагин предназначен для решения двух проблем: Когда WordPress обнаруживает, что используется FastCGI SAPI, код перенаправления, передаваемый в wp_redirect(), игнорируется. Таким образом, все перенаправления с кодом 301 тихо превращаются в перенаправления с кодом 302, что не очень хорошо для SEO. Если WordPress работает под управлением nginx, плагин переопределяет функцию wp_redirect(), что позволяет использовать коды перенаправления. Если WordPress [...]
← Вернуться к полной версии записи «nginx Compatibility»…
Автор: Vladimir;
Комментарии к статье «nginx Compatibility» (81) »
Пожалуйста, не используйте эту форму для комментирования! Данная форма предназначена исключительно для ботов.
Оставить комментарий к записи «nginx Compatibility»
गते गते पारगते पारसंगते बोधि स्वाहा
Меня зовут Владимир, я программист-фрилансер, специализирующийся на Web-программировании и програмировании под Linux.
По совместительству занимаюсь администрированием LAMP/LNMP-серверов и техническим переводом.


А для lighttpd такой плагин написать не желаете ?
Если Вы согласитесь его тестировать — без проблем (у меня нигде lighttpd не стоит).
Я бы так сказал, что я его уже заочно тестирую , хотя его еще даже нет
Вернее пока пытаюсь решить проблему отсутствия совместимого с wordpress mod_rewrite в lighttpd доступными способами, но если бы появилась такая , более удобная реализация, то я конечно потестировал бы её, потому как у меня как раз-таки сейчас lighttpd стоит…
Sorry, I do not speak Russian.
I downloaded and installed this plugin (version 0.2). Then I turned on permalinks. But when I visit a permalink, Nginx says, «404″.
This is the FastCGI section in my Nginx configuration. Maybe something is wrong?
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME /home/luser/public_html/blog.skeleton.com/public/$fastcgi_script_name;
}
I am using Nginx 0.7.59
No problem, I do speak English.
As for the configuration, it is not correct. Well, it is but not completely.
It should look like this (irrelevant blocks omitted):
listen ...;
server_name ...;
root /path/to/blog;
index index.php;
location / {
try_files $uri $uri/ @wordpress;
}
location @wordpress {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME /path/to/blog/index.php;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_NAME /index.php;
}
location ~ \.php$ {
try_files $uri @wordpress;
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME /path/to/blog$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
}
}
The key is
try_files. It is nginx’s counterpart for Apache’sRewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
When you access
http://example.com/my/permalink, nginx:/my/permalinkfile;/my/permalink/directory;location @wordpresssection which instructs it to useindex.phpand sets the correctSCRIPT_NAME(otherwise, All in One SEO Pack will bail out with fatal error).index.phplooks at$_SERVER["REQUEST_URI"]and handles all permalink stuff.Also please note the absense of the leading slash in
fastcgi_parambefore$fastcgi_script_name:$fastcgi_script_namealready contains that slash (e.g.,/index.php) and there’s no need to duplicate it.Hope that helps.
Wow, I think your English is better than mine!
Thank you very much for the fast response. There are many guides on nginx and wordpress, but many don’t have good explanation.
It’s good to see you posted code which works, and then a explanation of how it works.
I used the examples provided, and now permalinks work fine. Even though I didn’t enable your plugin yet. Is this code supposed to make the plugin unneeded, or should I turn it on still?
Thank you again for the big help!
You are always welcome.
If you just need to have working permalinks, you don’t have to enable the plugin. However, if you are concerned about SEO, you should probably activate the plugin.
When WordPress performs a redirect (using its
wp_redirect()function) it always sends 302 response code even if 301 (which transfers PR) should be used.Basically the plugin tricks WP into thinking that the server has the same capabilities as Apache (say, it supports pretty permalinks instead of PATHINFO, correctly interpretes 301 redirect etc) thus making WP enable all fetaures it disables when not running in Apache server.
Oh I remember now. You said about the redirects on the plugin page. Sorry!
Thanks for explain to me again!
Thanks for this plugin!
Getting permalinks to work with Wordpress on nginx isn’t much of a hassle, but I was disappointed to see redirects returning a 302. I wasn’t aware Wordpress would drop the redirect status code when PHP is running as CGI. Your plugin works exactly as described: «install and forget.»
You are welcome!
Поясните, плз. Этот плагин в любом случае полезен, или только когда апач с в связке с nginx?
Собсно как определить насколько необходимо его использование на конкретном хостинге?
Смотря какой из серверов занимается обработкой PHP. Если nginx — то да, если Apache — то нет.
Как определить — посмотрите, какую структуру постоянных ссылок предлагает WordPress. Если PATHINFO (
/index.php/something/else) — то нужен. Ну или посмотрите, выполняется ли редирект с кодом 301.Добрый день. Я приехал из отпуска. И вдруг обнаружил на своем вордпрессе проблему. При входе в админку я вижу предупреждение
Когда я изменяю имя папки с вашим плагином, чтобы отключить его, я вижу следующее
там определяется функция:
global $is_IIS;
$location = apply_filters('wp_redirect', $location, $status);
$status = apply_filters('wp_redirect_status', $status, $location);
if ( !$location ) // allows the wp_redirect filter to cancel a redirect
return false;
$location = wp_sanitize_redirect($location);
if ( $is_IIS ) {
header("Refresh: 0;url=$location");
} else {
if ( php_sapi_name() != 'cgi-fcgi' )
status_header($status); // This causes problems on IIS and some FastCGI setups
/*865 ->*/ header("Location: $location");
}
}
попробовал на угад закомментировать эту ветку кода
// if ( php_sapi_name() != 'cgi-fcgi' )
// status_header($status); // This causes problems on IIS and some FastCGI setups
// header("Location: $location");
// }
после чего, админка совсем не грузится, ни какого кода вордпресс в ответ вообще не отдает.
Что сделать с этим – не знаю… помогите пожалуйста… Какие могут быть варианты?
Конфиг: Gentoo + Nginx + PHP5 + MySQL5
Не знаю что за проблема была. Помогло обновиться до версии 2.8.4 с версии 2.8.2
curt, в сообщении об ошибке ясно сказано: .
Что-то не того в 55 строке в Вашем
wp-load.phpбыло. Возможно, пустая строка или вывод текста.[...] Nginx Compatibility Plugin für Wordpress [...]
[...] Vladimir Kolesnikov [...]
http://www.economatix.com/test-of-url-rewrite-without-htaccess[...] Vladimir Kolesnikov Spark [...]
[...] nginx Compatibility [...]
[...] nginx Compatibility [...]