简体   繁体   中英

.htaccess URL rewrite works, but address bar then shows 'dirty' URL

  • User clicks link (from their email): http://www.site.com/edit/wih293f73y
  • Browser window opens and gets them to the correct page.
  • But now the browser's address bar shows: http://www.site.com/editor.php?editCode=wih293f73y

Extra info:

  • My rewrite rule is: RewriteRule ^edit/([A-Za-z0-9-]+)/?$ editor.php?editCode=$1 [NC,L]
  • This problem ONLY occurs when the user has clicked a link. It works perfectly when you just type the pretty url into the address bar.
  • This problem ONLY occurs for links that include the www. - the link http://site.com/edit/wih293f73y works like a charm.
  • My .htaccess file includes the following code (from HTML5 boilerplate, which I wasn't aware of previously):
 # Rewrite www.example.com → example.com <IfModule mod_rewrite.c> RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^www\\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] </IfModule> 

If it's important, this occurs after my other rewrite rules.

I just took a look and it is apparent that your www rules is causing this. Question is do you want it be fixed? If you do then move this rule on top of all other rules and your problem should be fixed.

Move this to top of all other rules

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

You can use use the redirect directive

redirect 301 ^edit/([A-Za-z0-9-]+)/?$ editor.php?editCode=$1

There are some pros and cons to this strategy. The pros being;

  • It's super fast. You don't even need to load up your application for this to work.
  • It's minimal code.
  • Redirects are an intrinsic part of Apache (or any http server) and aren't going anywhere soon.

The cons being;

  • It's not part of your application proper. Should you decide to change logic or URLs, you'll have to change this, too.
  • It's slower, as you need to invoke php, as opposed to just having Apache issue the redirect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM