Question

I have a website done in Wordpress and I need to make some changes in the fiendly URLs.

I’ve created a page from the admin panel named detail, this page reads the template file detail.php from the templates folder.

The URL that is currently mounted is http://www.domain.com/detail/1234/ and I need that it could be accessed as http://www.domain.com/anything/1234/.

The following lines have been generated by Wordpress but I don’t understand them and I don’t know how to modify them for my purpose:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Était-ce utile?

La solution

First you should really understand what those rules are doing and what you really want to achieve. Then you can try to change the system to fit your needs.

IfModule ensures everything inside is processed only when mod_rewrite Apache module is present. All the other directives are from this module.

  1. RewriteEngine On enables URL rewriting.
  2. RewriteBase / tells the engine that the rules operate inside root. See also the general question on how RewriteBase works.
  3. RewriteRule ^index\.php$ - [L] means that no more rules should be processed ([L]) if the current URL to be rewritten is index.php. No rewrite takes place. RewriteRule directive accepts a regex. See also tag here on SO.
  4. All RewriteCond directives apply to the following RewriteRule. Unless [OR] flag is added, they must be all satisfied at the same time to execute the rule. In this case they mean:
    • Requested resource is not a regular file.
    • Requested resource is not a directory.
  5. Rewrite any (at least one character long) URL to index.php. This is the last ([L]) rule to be processed.

When adding new RewriteRules, you probably want to use the WordPress way of doing this, as described in Zac’s answer. Figuring out the right rule by analogy to the many examples in the manual or here on SO should not be hard.

Autres conseils

Put into functions.php maybe a better idea:

functions.php

function setRewriteRule($orgRules){
    return array( '/([^/]+)/([0-9]+)/?' => 'index.php?post=$matches[1]' ) + $orgRules;
}

add_filter('rewrite_rules_array', 'setRewriteRule');

Then you just need flush the rewrite rules, I usually use 'rewrite-rules-inspector' plugin.

This should solve your problem give it a try ... you can write your own custom permalink without adding any code also if someone tries to access the page via old URL they will be redirected to the new one.

WordPress Custom Permalinks

After installing this you just have to go into pages and type your own URL below the heading

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top