C.E.
C.E.

Reputation: 664

Mod-Rewrite "Canonical URL's"

Hy, how can i make canonical URLs (For Facebook "Parsing") with mod_rewrite.

Example: I have: example.com/index.php?page=eventdetails&id=241

I would make an canonincal URL, which should look like this:

example.com/eventdetails/241/some text which would be ignored from script

I tested it with this example, but it doesn't work:

RewriteEngine on
RewriteRule ^/eventdetails/([0-9]+)/$ index.php?show=eventdetails&id=$1

The .htaccess File is in the "home" direction.

I dont find any Solutions for exact this example @google, so i hope someone can help me!

Upvotes: 2

Views: 1108

Answers (1)

Book Of Zeus
Book Of Zeus

Reputation: 49887

Try this:

RewriteEngine on
RewriteBase /
RewriteRule ^eventdetails/([0-9]+)/?$ index.php?show=eventdetails&id=$1 [L,NC]
RewriteRule ^eventdetails/([0-9]+)/([a-z0-9\-_]+)/?$ php.php?show=eventdetails&id=$1&name=$2 [L,NC]

The /? means an optinal / at the end. So example.com/eventdetails/241/ and example.com/eventdetails/241 will work for this rule. The first one will only use the first rule if the event name is not use.

And this Url will use the second one (IF the event name is use): example.com/eventdetails/241/event-name/. Now here, I don't recommend the + since it's not really SEO friendly, maybe some will accept it but some not. I recommend the - instead.

I added the L in case you have other rules and NC flag for non-case.

L: The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.

NC: Use of the [NC] flag causes the RewriteRule to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URI.

from: http://httpd.apache.org/docs/2.3/rewrite/flags.html

Upvotes: 7

Related Questions