Add URL Rewrite Rule To Wordpress

2019-02-16 23:46发布

问题:

I've written a Wordpress plugin that adds a query string to the URL. However I can't seem to modify the htaccess to rewrite this. Not sure if Wordpress is overriding it?

The current htaccess is:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

And the URL I'm trying to rewrite is:

http://domain.com/deal-info/?id=87&post_name=testdealtitle

Desired URL:

http://domain.com/deal-info/87/testdealtitle

I've tried adding:

RewriteRule ^([^/]*)/([^/]*)$ /deal-info/?id=$1&post_name=$2 [L]

to no avail. Any ideas appreciated!

回答1:

When you do this:

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

This means: "if it's not a file, and if it's not a dir, redirect all incoming URLs to index.php.

Your rewriterule should work... unless you've put it after the previous rewriterule. So, in short, are you sure your .htaccess it like that:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^([^/]*)/([^/]*)$ /deal-info/?id=$1&post_name=$2 [L]
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

Please tell me if it works.


Moreover if you only want to redirect only deal-info, you should do something like (not tested):

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^(/)?deal-info/([^/]*)/([^/]*)$ /deal-info/?id=$2&post_name=$3 [L]
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

Two hints:


Please try to use the RewriteLog directive: it helps you to track down such problems:

# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On

My favorite tool to check for regexp:

http://www.quanetic.com/Regex (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)

May I ask you to add the rewritelog in your question?



回答2:

After much confusion I found an answer here: https://wordpress.stackexchange.com/questions/5413/need-help-with-add-rewrite-rule

Though I think the proper way to do it is by: http://codex.wordpress.org/Rewrite_API/add_rewrite_rule

I'm not sure if you can do this directly in htaccess, or I was having a conflict problem with another plugin I was using.

Thanks again to Olivier for his extensive answer!