Why does htaccess mod_rewrite always discard the query string in the target URL

I have the following logic in my .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule notes/(.*?) notes/?u=/$1
</IfModule>

However, for some reason this always removes the query string from the output. So, this is for example the result I git:

Read More
http://localhost:8888/notes/tifffilmtips   >   http://localhost/notes/

However, if I change the RewriteRule to RewriteRule notes/(.*?) notes/u=/$1, excluding the ? before the u=, the result is:

http://localhost:8888/notes/tifffilmtips   >   http://localhost/notes/u=/tifffilmtips

So for some reason, the output always discards the generated query string. Why would this be? I’ve tried different flags, but I can’t find one that works as expected, and I can’t find reference to other people having similar problems.


EDIT:

Here’s the complete htaccess with the first part working:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} ^$
RewriteBase /magazine/wordpress/
RewriteRule ^notes/(.*)$ notes/?u=/$1 [QSA,NC,L]
</IfModule>

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

# END WordPress

Related posts

Leave a Reply

2 comments

  1. Change your RewriteRule to this:

    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /magazine/wordpress/
    
    RewriteCond %{QUERY_STRING} ^$
    RewriteRule ^notes/(.*)$ notes/?u=/$1 [NC,L]    
    
    RewriteRule ^index.php$ - [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /magazine/wordpress/index.php [L]
    
    </IfModule>
    
  2. If /notes/ is being routed as a wordpress permalink, then this is going to be a bit painful as wordpress usually strips out the query string when you turn on permalinks. Take a look at this post which goes over why wordpress is doing this, how it’s doing it, and how to work around it. Permalinks in wordpress adds an additional layer of rewriting that’s internal to wordpress and query string parameters get blown away when that happens. So the fix involves adding some php code, specifically in your theme’s functions.php script. Something like:

    function add_query_vars($aVars) {
      $aVars[] = "u"; 
      return $aVars;
    }
    
    // hook add_query_vars function into query_vars
    add_filter('query_vars', 'add_query_vars');
    

    then:

    function add_rewrite_rules($aRules) {
      $aNewRules = array('notes/([^/]+)/?$' => 'index.php?pagename=notes&u=$matches[1]');
      $aRules = $aNewRules + $aRules;
      return $aRules;
    }
    
    // hook add_rewrite_rules function into rewrite_rules_array
    add_filter('rewrite_rules_array', 'add_rewrite_rules');