将.htaccess重写规则转换为PHP(Pantheon环境WordPress站点)
Convert Nginx Sitemap Rewrites to PHP for Pantheon WordPress
Hey there! I know dealing with regex and server configs can feel overwhelming, especially when Pantheon’s Nginx ignores .htaccess rules. Let’s turn those Nginx rewrite rules into working PHP code you can drop right into your wp-config.php file.
Here's the complete code to add to your wp-config.php
Make sure to place this before the line that says /* That's all, stop editing! Happy publishing. */:
add_action('parse_request', function($wp) { // Grab the current request URI $request_uri = $_SERVER['REQUEST_URI']; // Handle sitemap.xml or sitemap-xxx.xml if (preg_match('#^/sitemap(-+([a-zA-Z0-9_-]+))?\.xml$#', $request_uri, $matches)) { $param = isset($matches[2]) ? $matches[2] : ''; $wp->query_vars['xml_sitemap'] = "params={$param}"; $wp->request = 'index.php'; return; } // Handle sitemap.xml.gz or sitemap-xxx.xml.gz if (preg_match('#^/sitemap(-+([a-zA-Z0-9_-]+))?\.xml\.gz$#', $request_uri, $matches)) { $param = isset($matches[2]) ? $matches[2] : ''; $wp->query_vars['xml_sitemap'] = "params={$param};zip=true"; $wp->request = 'index.php'; return; } // Handle sitemap.html or sitemap-xxx.html (completed based on your partial rule) if (preg_match('#^/sitemap(-+([a-zA-Z0-9_-]+))?\.html$#', $request_uri, $matches)) { $param = isset($matches[2]) ? $matches[2] : ''; // Adjust the query string here if your actual target is different $wp->query_vars['xml_sitemap'] = "params={$param};format=html"; $wp->request = 'index.php'; return; } });
What this code does:
- We use WordPress’s
parse_requestaction to intercept incoming requests before they’re fully processed. - Each
preg_matchchecks the request URI against your original Nginx regex (adjusted for PHP syntax). - For matching requests, we set the
xml_sitemapquery variable exactly like your Nginx rules did—including handling the optionalxxxparameter and thezip=trueflag for gzipped sitemaps. - We tell WordPress to route the request to
index.phpso your sitemap plugin can handle the query parameters properly.
A quick note on the partial third rule:
Your original third rewrite rule was cut off, so I assumed it should point to a similar query string with an HTML format flag. If your actual target is different (like a unique query parameter), just modify the line starting with $wp->query_vars['xml_sitemap'] in that last block to match what you need.
内容的提问来源于stack exchange,提问作者joakland
相关产品推荐
相关产品推荐

