WordPress:自定义重写规则 - .htaccess或functions.php?

Sta*_*erg 2 wordpress mod-rewrite

我要疯了.我唯一想做的就是将这些规则添加到我正在开发的网站中:

fastigheter-spanien/x    property/X&lang=sv
fastigheter-usa/x    property/X&lang=sv
properties-spain/X    property/X&lang=en
properties-usa/X    property/X&lang=en
Run Code Online (Sandbox Code Playgroud)

其中X是帖子的名称.这些都是自定义帖子类型.我最终遇到这种情况的原因是我使用多种语言,但希望客户端不必为每篇文章创建多个帖子(他们有很多选项和图片,不得不重新发布它们几乎不属于题).我已经研究过在functions.php中创建rewrite_rules以及修改.htaccess文件但是无法让它工作.这些重写非常简单,不需要使用任何函数.我不能只调整.htaccess文件吗?

试着

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !^/fastigheter-spanien/([^\./]+)
RewriteCond %{REQUEST_URI} !^/fastigheter-usa/([^\./]+)
RewriteCond %{REQUEST_URI} !^/properties-spain/([^\./]+)
RewriteCond %{REQUEST_URI} !^/properties-usa/([^\./]+)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteRule ^fastigheter-spanien/([^\./]+)$ property/$1 [L]
RewriteRule ^fastigheter-usa/([^\./]+)$ property/$1 [L]
RewriteRule ^properties-spain/([^\./]+)$ property/$1&lang=sv [L]
RewriteRule ^properties-usa/([^\./]+)$ property/$1&lang=sv [L]
Run Code Online (Sandbox Code Playgroud)

这只是给了我404.任何想法?

Tim*_*one 6

您的重写应该正常工作,但WordPress看不到您的修改.这样做的原因是WordPress读取$_SERVER['REQUEST_URI'],它将始终包含原始请求URI,而不是来自mod_rewrite操作的结果.

我对实际使用WordPress并不熟悉,但我已经查看了其他一些问题的一些源代码$_SERVER['PATH_INFO'],如果提供的话,它似乎也会尝试使用.因此,你可以试试这个:

AcceptPathInfo On
RewriteEngine On
RewriteBase /

RewriteRule ^fastigheter-(spanien|usa)/([^\./]+)$ property/$2&lang=sv
RewriteRule ^properties-(spain|usa)/([^\./]+)$    property/$2&lang=en

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /index.php/$0 [L]
Run Code Online (Sandbox Code Playgroud)

我发现PATH_INFO虽然使用是有问题的(并且通常不会在每个目录的上下文中工作,虽然我不认为我已经确定了原因),并且通常建议不要使用它.

你的另一个选择也涉及PHP方面的工作.你可以做一些类似于Anraiki建议的事情,或者你可以说出$_SERVER['REQUEST_URI']你正在期待的事情.

如果mod_rewrite执行重定向,则REQUEST_URI模块看到它存储在服务器的REDIRECT_URL变量中.因此,稍微调整重写规则集,我们可以这样做:

RewriteEngine On
RewriteBase /

# Force L on these rules to cause the REQUEST_URI to be changed (so that
# REDIRECT_URL will end up with the rewritten value we want)
RewriteRule ^fastigheter-(spanien|usa)/([^\./]+)$ property/$2&lang=sv [L]
RewriteRule ^properties-(spain|usa)/([^\./]+)$    property/$2&lang=en [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
Run Code Online (Sandbox Code Playgroud)

然后,在WordPress处理的早期某处(例如index.php,因为您不太可能需要使用后续的WordPress版本更新该文件),您可以执行以下操作:

if (!empty($_SERVER['REDIRECT_URL']))
    $_SERVER['REQUEST_URI'] = $_SERVER['REDIRECT_URL'];
Run Code Online (Sandbox Code Playgroud)

很可能有一种方法可以使用固定链接设置本身在WordPress中定义您的行为,因为它在解析请求时会迭代该规则列表,但我并不完全清楚这个细节因为我从未使用过我自己.如果这是可能的,我会认为这是处理这种情况的推荐方法,但无论哪种方式,希望这些选项之一应该让事情适合你.