I’m trying to get Nginx and WordPress to play nice together.
Most of the documentation I’ve found talks about how to set up Nginx rewrite rules for WP Multisite configurations, but I’m trying to do something slightly different, where I’m looking to load data from an API and populate a template wordpress page, but have the url as the last path component.
For example I’m trying to load a page with a URL like this…
http://example.com/article/{the-slug}
When loading this page we want to redirect to a WordPress page located at a permalink of this
We do no want to load any post content from the existing word press site,
We simply always go to this page when any url matching /article/{slug} is matched, and pass off the slug parameter behind the scene.
We have a WP Rewrite rule in place in our theme’s functions.php
/**
* Intercept the articles request
* @return void
*/
function custom_rewrite_rule() {
add_rewrite_rule('^article/([^/]*)/?','index.php/article?slug=match[1]','top');
}
add_action('init', 'custom_rewrite_rule’);
When running in Apache everything works exactly as expected when the following rules specified in the .htaccess file.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteRule ^^article/([^/]*)/? /index.php/article?slug=match[1] [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
However I’ve tried to convert this to run on Nginx with no success.
Some variations I’ve used for the location directive are
location / {
rewrite ^/^article/([^/]*) /index.php/article/?slug=match[1];
try_files $uri $uri/ /index.php$query_string;
}
And
location / {
try_files $uri $uri/ ^article/([^/]*)/? /index.php/article?slug=match[1];
try_files $uri $uri/ /index.php$query_string;
}
And even a combo of these together.
location /article {
try_files $uri $uri/ ^article/([^/]*)/? /index.php/article?slug=match[1];
}
location / {
try_files $uri $uri/ /index.php$query_string;
}
But I’m really stumped on the actual syntax to get this to work
Any advice would be greatly appreciated.
Thanks.
Update
I’ve been logging rewrites in Nginx and things there look like they’re doing exactly what they should
2016/06/16 02:56:52 [notice] 12879#12879: *1 "^/article/(.+)" matches "/article/test-article", client: 192.168.10.1, server: example.com, request: "GET /article/test-article HTTP/1.1", host: "example.com"
2016/06/16 02:56:52 [notice] 12879#12879: *1 rewritten data: "/index.php/article", args: "", client: 192.168.10.1, server: example.com, request: "GET /article/test-article HTTP/1.1", host: "example.com"
And if I place this url in the browser http://example.com/index.php/article/, I go exactly where i want the rewrite to take me.