Showing posts with label mod-rewrite. Show all posts
Showing posts with label mod-rewrite. Show all posts

Monday, September 10, 2018

How to redirect multiple domains to woocommerce product page dynamically?

Leave a Comment

Consider abc.com is my main website using nameservers ns1.testnameserver.com & ns2.testnameserver.com.

I would like to redirect multiple domains as below:

def.com to abc.com/products/def ghi.com to abc.com/products/ghi jkl.com to abc.com/products/jkl mno.com to abc.com/products/mno 

I tried the below:

i set the same testnameserver for def.com,ghi.com,jkl.com,mno.com.

tried some combination in RewriteCond and .htaccess but i couldn't solve it.

Anyone guide me to move further.

Thanks all.

Note:

I can't use domain forwarding / host all the domains because it's should be dynamic (like 3500+ domains to 3500+ products)

3 Answers

Answers 1

You can achieve this using below steps -

  1. You need to setup the zone file for each domain having an A record entry pointing to IP address of abc.com.

  2. On abc.com web server, you can write an script in any language of your choice which will read the host and appropriately does a redirect to wherever you need.

Alternatively you could do this from .htacess too, but since you have a large amount of domains, so I would suggest to go with a script in any language (php, python etc.)

Answers 2

You can do exactly what you are looking for with a RewriteMap directive.

First place your mappings in a file, e.g. /var/lib/domains.txt containing

def.com     http://example.net/products/def ghi.com     http://example.net/products/ghi jkl.com     http://example.net/products/jkl mno.com     http://example.net/products/mno 

Then you set up the following rules in a server or virtual host .conf -file (you cannot do this in a .htaccess file):

RewriteEngine On  RewriteMap      lowercase       int:tolower RewriteMap      custdomains     txt:/var/lib/domains.txt  # rewrite matching domain to desired URL RewriteCond     ${lowercase:%{HTTP_HOST}}       ^(?:www\.)?(.+) RewriteCond     ${custdomains:%1}               ^(.+)$ RewriteRule     ^/(.*)$                         %1              [R=301,L,NE]  # unmatched domains are passed unchanged RewriteRule     .                               -               [R,NE,L] 

The RewriteCond -rules will capture the HTTP_HOST header containing the hostname of the target domain the user is browsing to. If that hostname matches a mapping defined in your textfile, the browser will be redirected to the matching URL.

With this setup you can point all your thousands of domains to the same server, which then performs suitable redirects based on the mappings in an external file (which you can update without having to restart apache). For better performance, you should really use an external DBM Hash File instead (see the documentation for RewriteMap for details).

Answers 3

I'm not sure I understand your problem, but you can redirect domains with:

RewriteEngine on  # not for exemple.com RewriteCond %{HTTP_HOST} !example\.com$ [NC] RewriteCond %{HTTP_HOST} (?:^|\.)([^.]+)\.(?:[^.]+)$ RewriteRule ^ http://example.com/products/%1%{REQUEST_URI} [NE,L]  

Point all your DNS on the main website, and just change the name of the main domain (example.com) in this .htaccess

Read More

Monday, August 6, 2018

Error adding the same .htaccess rule more than once?

Leave a Comment

I have the following rule that allows me to create, multiple categories, in the URL, without needing to write the categories in my .htaccess, for example: RewriteRule ^ global / (...

I do it directly from the following rule:

RewriteRule ^(.*)/([^/]+/?)$ product.php?id=$2&categories=$1 RewriteRule ^(.*)/([^/]+/?)$ product_one.php?id=$2&categories=$1 

With my rule I can have a number of categories in the URL, for example:

example.com/category/gloabl/others/plus/my-url-article-post/ 

Now my problem is, that I have individual product details, created by individual files product.php, product_one.php among others.

Which only works one of the .htaccess rules, that is, I have to deactivate # one of them, so that the details of the products in the detail.php file show the details and to show the detail of the file detail_one.php I have to disable the .htaccess rule in the detail.php file

How can I do to keep the same design of multiple categories, but that the same rule allows me to add more than one, for the different news details?

0 Answers

Read More

Wednesday, December 6, 2017

Exclude specific subdomain or no subdomain in htaccess RewriteRule

Leave a Comment

I keep dynamic content and static content on different sub domains for my web app but I've recently found out that if called directly the dynamic content can be viewed on my static subdomain (www.) or no subdomain at all.


URL Structure:

http(s)://(subdomain).(domain).(tld)/(static page) OR (direct/random hash) OR (secure/random hash) 

All static content is accessible via "WWW" which results in my SEO friendly domains such as

http(s)://www.domain1.com/about http(s)://www.domain1.com/ http(s)://www.domain2.com/about http(s)://www.domain2.com/ 

While dynamic content viewed through the web app would be accessed from a domain such as

http(s)://dynamic1.domain1.com/direct/randomhash http(s)://dynamic2.domain1.com/direct/randomhash http(s)://dynamic1.domain2.com/direct/randomhash http(s)://dynamic2.domain2.com/direct/randomhash 

This is my current .htaccess file

The rules to rewrite the dynamic links where the URI starts with secure or direct as well as any file extensions to the index.php file.

Header set Connection keep-alive <IfModule mod_dir.c>     DirectorySlash Off </IfModule> <IfModule mod_rewrite.c>     RewriteEngine On     RewriteRule ^index.php  - [L]     RewriteRule ^(secure|direct)  /index.php [L]     RewriteCond %{REQUEST_URI} !^/server-status     RewriteCond %{REQUEST_URI} !^/public/cache     RewriteRule !\.(png|gif|css|jpg|zip|js|html|htm|swf|ico|fon|ttf|otf|svg|woff|woff2|eot)$  /index.php [L] </IfModule> 

The above is currently working but my issue is that if a user simply changes the sub domain from the one used for dynamic content to WWW it will still work and will result in dynamic content being accessible from my SEO friendly sub domain.

I'm hoping to be able to edit this rule RewriteRule ^(secure|direct) /index.php [L] so that it would be excluded if there is an active www. sub domain or no subdomain all together while still working if the domain or subdomain is anything else.

That is to say the subdomain or domain would still be a wildcard unless the subdomain is www.


I'm assuming I have to add %{HTTP_HOST} to the RewriteRule ^(secure|direct) /index.php [L] and use a regex to allow any sub domain, domain, and tld but im not sure how to exclude if the http host starts with WWW. or no subdomain at all.

My end goal is so that the secure and direct paths can not be viewed via a www. or no subdomain while still working with any other subdomain / domain.

2 Answers

Answers 1

You can use:

RewriteCond %{HTTP_HOST} ^(?:www\.)?[^.]+\.[^.]+$ [NC] RewriteRule ^(secure|direct)  /index.php [L] 

Answers 2

You should add a condition to the rule that handles 'secure' and 'direct' requests, so that they have to only come from the subdomains you match, not the www one.

RewriteCond %{HTTP_HOST}  ^dynamic[0-9]+\.[a-z]+  RewriteRule ^(secure|direct)  /index.php [L] 

That way only requests that have subdomains matching that rule will get re-written to the PHP script. If the user changes the sub-domain back to www, or to anything else that doesn't match the pattern you specify in the condition, then the request won't find its way through to the PHP script.

If your names for dynamic sub-domains are truly random, then just use something else that you know about them so that 'www' doesn't match, for example if they're all at least four characters long then this pattern would work:

RewriteCond %{HTTP_HOST}  ^[^.][^.][^.][^.]+\.  RewriteRule ^(secure|direct)  /index.php [L] 

because the string 'www.' does not match a pattern starting with four or more non-dots and then a dot.

Read More

Sunday, November 26, 2017

301 redirect non-www to www

Leave a Comment

I am trying to redirect all non-www to www on my website! My SSL is already configured to redirect all http to https but all what I have found is working only partially for me!

if I type mysite.com/en/articles/12/how-to-code, for example I am redirected to www.mysite.com/index.php which should have been www.mysite.com/en/articles/12/how-to-code

I have tried solutions to this SO question, I know this question is a possible repeat but other solutions have not worked for me! Am using apache2.

This my .htaccess in the /public folder

<IfModule mod_rewrite.c>     <IfModule mod_negotiation.c>         Options -MultiViews     </IfModule>      RewriteEngine On      # Redirect Trailing Slashes If Not A Folder...     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule ^(.*)/$ /$1 [L,R=301]      # Handle Front Controller...     RewriteCond %{REQUEST_FILENAME} !-d     RewriteCond %{REQUEST_FILENAME} !-f     RewriteRule ^ index.php [L]      # Handle Authorization Header     RewriteCond %{HTTP:Authorization} .     RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]      # Redirect to www     RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$     RewriteCond %{HTTPS}s ^on(s)|     RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> 

Thanks in advance

1 Answers

Answers 1

Change the order, and redirect before rewrite:

<IfModule mod_rewrite.c>     <IfModule mod_negotiation.c>         Options -MultiViews     </IfModule>      RewriteEngine On      # Redirect Trailing Slashes If Not A Folder...     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule ^(.*)/$ /$1 [L,R=301]      # Redirect to www     RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$     RewriteCond %{HTTPS}s ^on(s)|     RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]      # Handle Front Controller...     RewriteCond %{REQUEST_FILENAME} !-d     RewriteCond %{REQUEST_FILENAME} !-f     RewriteRule ^ index.php [L]      # Handle Authorization Header     RewriteCond %{HTTP:Authorization} .     RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] </IfModule> 

Because if you redirect after rewriting the URL, this is the last version that will be modified and returned for the redirection request.

Read More

Friday, August 4, 2017

.htaccess internal redirect not working with string parameter

Leave a Comment

So i have been on this for hours but can't get it to resolve. Nothing on stackoverflow tackles my issue. The issue is that i have a redirect rule in my .htaccess as follows

RewriteRule ^store-category/(.+)/?$ /wordpress/store-category/?cid=$1 [QSA,L] 

This redirect works when cid is a number but when a use a string like "my-key" it does not work. With the key i have to change the rule to this.

RewriteRule ^store-category/(.+)/?$ /wordpress/store-category/?cid=$1 [R,L] 

However i do not want to use this because this redirects my users visibly and the url changes, which i don't want. Can anyone please explain why this thing is working for numbers but not for string parameters. Any help would be appreciated.

Edit: Complete .htaccess

# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /wordpress/ RewriteRule ^index\.php$ - [L] RewriteRule ^store-category/(.+)/?$ /wordpress/store-category/?cid=$1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /wordpress/index.php [L] </IfModule>  # END WordPress 

4 Answers

Answers 1

I did some try on local and found that it works for me if I put these two rules:

RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d 

even before the row

RewriteRule ^store-category/(.+)/?$ /wordpress/store-category/?cid=$1 [QSA,L] 

Complete .htaccess file will be:

<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /wordpress/  RewriteRule ^index\.php$ - [L]  RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^store-category/(.+)/?$ /wordpress/store-category/?cid=$1 [QSA,L]  RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /wordpress/index.php [L] </IfModule> 

Anyway, with (.+)/?$, an eventual trailing slash will be captured from the group and will go on the cid parameters. If categories doesn't have slashes inside, it's better to use ([^/]+)/?$.

Update: The understand what happen on your redirects, enable the log (see http://httpd.apache.org/docs/current/mod/mod_rewrite.html fo this). On my host I enabled mod_rewrite.c:trace3 and I get the following log in error_log (just tracking lines with rewrite)

[Fri Aug 04 12:48:56.904099 2017] [rewrite:trace3] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] [perdir /var/www/localhost/htdocs/wordpress/] strip per-dir prefix: /var/www/localhost/htdocs/wordpress/store-category/my-id -> store-category/my-id [Fri Aug 04 12:48:56.904123 2017] [rewrite:trace3] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] [perdir /var/www/localhost/htdocs/wordpress/] applying pattern '^index\\.php$' to uri 'store-category/my-id' [Fri Aug 04 12:48:56.904129 2017] [rewrite:trace3] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] [perdir /var/www/localhost/htdocs/wordpress/] strip per-dir prefix: /var/www/localhost/htdocs/wordpress/store-category/my-id -> store-category/my-id [Fri Aug 04 12:48:56.904132 2017] [rewrite:trace3] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] [perdir /var/www/localhost/htdocs/wordpress/] applying pattern '^store-category/(.+)/?$' to uri 'store-category/my-id' [Fri Aug 04 12:48:56.904143 2017] [rewrite:trace2] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] [perdir /var/www/localhost/htdocs/wordpress/] rewrite 'store-category/my-id' -> '/wordpress/store-category/?cid=my-id' [Fri Aug 04 12:48:56.904147 2017] [rewrite:trace3] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] split uri=/wordpress/store-category/?cid=my-id -> uri=/wordpress/store-category/, args=cid=my-id [Fri Aug 04 12:48:56.904151 2017] [rewrite:trace2] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] [perdir /var/www/localhost/htdocs/wordpress/] trying to replace prefix /var/www/localhost/htdocs/wordpress/ with /wordpress/ [Fri Aug 04 12:48:56.904155 2017] [rewrite:trace2] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] [perdir /var/www/localhost/htdocs/wordpress/] trying to replace context docroot /var/www/localhost/htdocs with context prefix  [Fri Aug 04 12:48:56.904158 2017] [rewrite:trace1] [pid 22823:tid 140368028878592] mod_rewrite.c(477): [client ::1:58312] ::1 - - [localhost/sid#788520][rid#7fa9e4002970/initial] [perdir /var/www/localhost/htdocs/wordpress/] internal redirect with /wordpress/store-category/ [INTERNAL REDIRECT] 

(followed by some other logging while it try to find the default document index.php)

Answers 2

Regex is greedy (left to right). You're pulling in extra slashes possibly other things. I find it easiest to use not classes for URLs (rarely '.' which will match everything).

RewriteRule ^store-category/([^\/]+)/?$ store-category/?cid=$1 [QSA,L] 

You may also be able to simplify to this, depending on how you want to handle urls that may be malformed after the store category id.

RewriteRule ^store-category/([^\/]+) store-category/?cid=$1 [QSA,L] 

EDIT: You are right. I didn't test the whole htaccess. You're specifying the wordpress path twice one in rewritebase and again in the rule. I have updated the rules above, as well as providing a link to the updated solution in a tester:

http://htaccess.mwl.be?share=116de701-cf8a-577c-bab5-5c357d844452

Answers 3

Use this, this is successfully working for me i hope it will works for you.

RewriteEngine on IndexIgnore *  RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond $1 !^(index\.php|img|robots\.txt) RewriteRule ^(.*)$ index.php/$1 [L]  RewriteRule ^wordpress/index.php/.*$ - [F,L,NC] 

Answers 4

Have yo tried this? This was worked for me in my WP site.

RewriteCond %{REQUEST_URI}  ^/page\.php$ RewriteCond %{QUERY_STRING} ^id=(.+)/?$ RewriteRule ^(.*)$ http://example.site/page/%1.pdf [R=302,L] 
Read More

Thursday, June 29, 2017

.HTACCESS Redirection Issues

Leave a Comment

Namely, I have this .htaccess command...

RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([^\x00-\x7F]+).*$ ?open=encyclopedia&letter=$1&term=$0 [R,B,L,QSA] RewriteRule ^([A-Z](?:[^\x00-\x7F]+|[A-Z])?).*$ ?open=encyclopedia&letter=$1&term=$0 [R,B,L,QSA] 

...And I have two issues with it now:
Issue 1 - It loads shorthand of all of the letters except A, S and O. It displays blank white page instead of the actual page.
Issue 2 - When I enter http://example.com/Šandi (Astronomy), instead of redirecting me normally to http://example.com/?open=encyclopedia&letter=Š&term=Šandi+(Astronomy), the URL is http://example.com/?open=encyclopedia&letter=%25c5%25a0&term=%25c5%25a0andi+%2528Astronomy%2529

In other words:
• When I remove the [R] flag from either of the Rules, the shorthand URL (id est - example.com/A-O-S) is as described in Issue 1.
• When I add the [R] flag, it redirects inappropriately, as described in Issue 2, and it does not display the page.

Note: These problems include English and non-English letters (Š/Đ/Č/Ć/Ž).

As @anubhava suggested:
<?php print_r($_GET); ?> with [R] flag:
English: Array ( [open] => encyclopedia [letter] => V [term] => Vodolija (Astrologija) )
URL: ?open=encyclopedia&letterV&term=Vodolija (Astrologija)
Non-English: Array ( [open] => encyclopedia [letter] => ? [term] => Škorpija (Astrologija) )
URL: ?open=encyclopedia&letter=%c5&term=%c5%a0korpija%20(Astrologija)

<?php print_r($_GET); ?> without [R] flag:
English: Array ( [open] => encyclopedia [letter] => V [term] => Vodolija (Astrologija) )
URL: /Vodolija (Astrologija)
Non-English: Array ( [open] => encyclopedia [letter] => Š [term] => Škorpija (Astrologija) )
URL: /Škorpija (Astrologija)

As for the Index pages:
A - Array ( [open] => encyclopedia [letter] => A [term] => A ): It doesn't display the page, it shows blank white page.
O - Array ( [open] => encyclopedia [letter] => O [term] => O ): It doesn't display the page, it shows blank white page.
S - Array ( [open] => encyclopedia [letter] => S [term] => S ): It doesn't display the page, it shows blank white page.
As for the all the other Index pages, URL is Array ( [open] => encyclopedia [letter] => AnyLetter [term] => SameAnyLetter): It displays the page correctly... ...I do not see logic in it.

This is the new code:

RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] #1 RewriteRule ([A-Z](?:[^\x00-\xFF].|\w).*) ?open=encyclopedia&letter=$2 [R,B,NE,L,QSA] # it loads DZH, but not the rest #2 RewriteRule (([\x00-\xFF].|\w).*) ?open=encyclopedia&letter=$2 [R,B,NE,L,QSA] # it loads A-O-S and it loads DJ-ZH-LJ-NJ-SH RewriteRule ^([A-Z](?:[^\x00-\x7F]+|[A-Z])?).*$ ?open=encyclopedia&letter=$1&term=$0 [B,NE,L,QSA] 

When I delete the line #1, the line #2 is working fine. When I delete the line #2, the line #1 is working okay. But they won't work together. The line #2 displays all the letters except for the DŽ, and redirects properly. The line #1 displays only the letter DŽ properly, won't redirect and won't load the rest. With the line #2 enabled, the URL with /DŽ redirects to /?open=encyclopedia&letter=D%c5

UPDATE #6:

With the following code...

RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ((LJ).*) ?open=encyclopedia&letter=$2&term=$1 [R,NE,L,QSA] RewriteRule ((NJ).*) ?open=encyclopedia&letter=$2&term=$1 [R,NE,L,QSA] RewriteRule ((D\xC5\xBD).*) ?open=encyclopedia&letter=$2&term=$1 [R,NE,L,QSA] RewriteRule (([\x00-\xFF].|\w).*) ?open=encyclopedia&letter=$2&term=$1 [R,NE,L,QSA] 

...This happens:
• INDEX Pages: As for the „double-letter“ letters, it opens every letter correctly. As of the single letters, it loads every letter except A, O and S.
• TERM Pages: Considering it won't open A, O and S, therefore it won't open their Terms pages.
• /Lav (Astrologija) doesn't redirect to /?open=encyclopedia&letter=L&term=Lav (Astrologija), but instead redirects to /?open=encyclopedia&letter=L&term=Lav+%2528Astrologija%2529 thus won't open the proper page.
• It opens /Š properly and it redirects /Škorpija (Astrologija) properly to /?open=encyclopedia&letter=Š&term=Škorpija (Astrologija)
• It opens /Đ properly and it redirects /Đavo properly to /?open=encyclopedia&letter=Đ&term=Đavo
• Although it opens /U properly, /Unuk Al Haj redirects to /?open=encyclopedia&letter=Un&term=Unuk%20Al%20Haj, not opening the right page.
• Although it opens /U properly, /Ugaoni Razmak redirects to /?open=encyclopedia&letter=Ug&term=Unuk%20Al%20Haj, not opening the right page.
• Although it opens /R properly, /Ribe (Astrologija) redirects to /?open=encyclopedia&letter=Ri&term=Ribe (Astrologija), not opening the right page.
• Although it opens /V properly, /Vaga (Astrologija) redirects to /?open=encyclopedia&letter=Va&term=Vaga (Astrologija), not opening the right page.
• Although it opens /U properly, /Umerenost redirects to /?open=encyclopedia&letter=Um&term=Umerenost, not opening the right page.
• Although it opens /K properly, /Kuće (Astrologija) redirects to /?open=encyclopedia&letter=Ku&term=Kuće (Astrologija), not opening the right page.

2 Answers

Answers 1

It seems to me that you should be able to use:

RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L]  RewriteRule ^(.)[^/]*$ ?open=encyclopedia&letter=$1&term=$0 [L,QSA] 

Answers 2

Use NE (no escape) flag:

# here are all 2 letters which we count as 1  RewriteRule ((D\xC5\xBD).*) ?open=encyclopedia&letter=$2&term=$1 [R,NE,L,QSA] # C5 BD is utf8 encoding of Ž RewriteRule ((LJ).*) ?open=encyclopedia&letter=$2&term=$1 [R,NE,L,QSA] RewriteRule ((NJ).*) ?open=encyclopedia&letter=$2&term=$1 [R,NE,L,QSA]  # one letter RewriteRule (([\x80-\xFF].|\w).*) ?open=encyclopedia&letter=$2&term=$1 [R,NE,L,QSA] 
Read More

Saturday, June 24, 2017

Apache mod_rewrite for specific folders and paths

Leave a Comment

I have found dozens of articles online on how to setup mod_rewrites but for the love of God I can't figure out how to PROPERLY force HTTPS on ALL pages and after that force HTTP on certain directories or (already rewritten) pages.

Now this one gets really tricky as I need HTTPS on this directory, except for two cases, such as "/surf" which actually is rewritten from "surf.php", and "promote-([0-9a-zA-Z-]+)$" which is rewritten from "promote.php?user=$1" :

<Directory /home/rotate/public_html/ptp/>     AllowOverride None     Order Deny,Allow     Allow from all  Options +SymLinksIfOwnerMatch ErrorDocument 404 "<h1>Oops! Couldn't find that page.</h1>" RewriteEngine On RewriteRule ^promote-([0-9]+)$ promote.php?user=$1 [QSA,NC,L] RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php [L]  </Directory> 

I have tried some stuff but which only resulted in some weird redirection loops...

RewriteCond %{HTTPS} on RewriteRule !^(surf|promote-([0-9]+)$) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 

So basically I need to force HTTPS everywhere in /ptp/ except /ptp/surf (which is rewritten from surf.php AND /ptp/promote-123 which is rewritten from promote.php?user=123

Currently I'm using PHP to redirect to HTTP or HTTPS as per my needs but I know that it would be much faster if I could manage to do it via rewrites. Any pointers, tips, suggestions? Thanks.

UPDATE2: This worked:

RewriteCond %{HTTPS} off RewriteRule !^(surf|promote(-[0-9]+)?) https://%{HTTP_HOST}%{REQUEST_URI} [R=301]  RewriteRule ^promote-([0-9]+)$ promote.php?user=$1 [NC,L] RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php 

However, the resources such as javascript, fonts etc, were being blocked by the browser, unless I specified absolute HTTPS paths. Note that this never happened when redirecting through PHP...

2 Answers

Answers 1

I changed a little bit and it works perfectly

Changes

Remove the Change the RewriteRule to match file to .php to bottom.

Remove the $ sign that is End of the pattern

As Said in the update promote-1111 will redirect to promote.php?user=$1 change the promote-[0-9]+ to promote(-[0-9]+)? otherwise it will override in the second redirection as you redirecting it to promote.php?user=$1

The Code

RewriteCond %{HTTPS} off RewriteRule !^(surf|promote(-[0-9]+)?) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php [L] 

The page surf

enter image description here

The Page Index

Never mind the error message shown in this image. Since I tried it from my localhost, it won't have a certificate.

Will work with servers

enter image description here

Answers 2

Your rules aren't in the "update" working because of side effects of using <Directory> context. Each substitution starts processing again.

When you request /promote-123 and rewrite it to put the numbers in the query string, you can't then match the numbers as if they're still in the path. You'll need to match the rewriten path and the numbers with RewriteCond %{QUERY_STRING} (if you care about the numbers)

Read More

Monday, May 15, 2017

.htaccess file not redirecting assets to other domain

Leave a Comment

I'm trying to make my PHP site pull images in /assets/u/ from another server using a redirect in the .htaccess file. The .htaccess is definitely being used. I know because I set 'AllowOverride All' in the sites root directory in HTTPD config and even tested it by putting in incorrect syntax on purpose and confirming that I get an internal server error. But my images in /assets/u/ still aren't being pulled from the other server. Below is my .htaccess file...

SetEnv APPLICATION_ENV production  RewriteEngine On RewriteBase /  RewriteCond %{HTTP_HOST} !^((www)|(draft))\. RewriteRule ^(.*?)\/*$ http://www.%{HTTP_HOST}/$1 [R=301,L]  # Start of attempted redirect # RewriteCond %{REQUEST_URI} ^.*(/assets/u/).*$ [NC] RewriteRule ^assets/(.*)$ http://assets.otherserver.com/$1 [L,R=301] # End of attempted redirect #  RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] 

2 Answers

Answers 1

I don't fully understand your question but here is my 1st attempt.

I am assuming you are using assets/u/ as link in <img href="assets/u/test.jpg"> tag, and your actual files are stored in http://assets.otherserver.com address,

For this task I suggest you to use mod_proxy to display your images without redirecting the urls try with below rule I am assuming you are able to arrange your .htaccess without breaking the other rules.

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} ^/assets/u/(.+?)$ RewriteRule ^ http://assets.otherserver.com/%1 [P,L] 

For above rule to work you must have enabled below.

LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule proxy_module modules/mod_proxy.so 

Uncomment above lines in httpd.conf.

Inform me of any update.

Answers 2

As you use RewriteBase Directive, try to remove the the first /

RewriteCond %{REQUEST_URI} ^(assets/u/).*$ [NC] 
Read More

Tuesday, April 18, 2017

Is there an alternative of RewriteRule / .htaccess for a Python http.server.HTTPServer?

Leave a Comment

Can my server module (with http.server.HTTPServer) use something like the RewriteRule for redirect all traffic into a single cgi script? I'd like to be able to do what's shown here in this other question, but for my python server.

Can it be done using something like .htaccess, or is there another way?

Also, can this be done even for a simple localhost development server?
I am serving files for development via, for example, http://localhost:8000/html/index.html, and I would like to hide the /html subfolder from the URL even in development.
How can that be achieved?

1 Answers

Answers 1

You can use a custom script to initialize your server and define your Routes in it, such as suggested in this article.

Python 2:

server.py

import os import posixpath import urllib import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler  # modify this to add additional routes ROUTES = (  <- this is the "good stuff", make aliases for your paths     # [url_prefix ,  directory_path]     ['/media', '/var/www/media'],     ['',       '/var/www/site']  # empty string for the 'default' match )   class RequestHandler(SimpleHTTPRequestHandler):      def translate_path(self, path):         """translate path given routes"""          # set default root to cwd         root = os.getcwd()          # look up routes and set root directory accordingly         for pattern, rootdir in ROUTES:             if path.startswith(pattern):                 # found match!                 path = path[len(pattern):]  # consume path up to pattern len                 root = rootdir                 break          # normalize path and prepend root directory         path = path.split('?',1)[0]         path = path.split('#',1)[0]         path = posixpath.normpath(urllib.unquote(path))         words = path.split('/')         words = filter(None, words)          path = root         for word in words:             drive, word = os.path.splitdrive(word)             head, word = os.path.split(word)             if word in (os.curdir, os.pardir):                 continue             path = os.path.join(path, word)          return path  if __name__ == '__main__':     BaseHTTPServer.test(RequestHandler, BaseHTTPServer.HTTPServer) 

Then run your script:

python server.py 

Python 3:

In Python 3 the BaseHTTPServer and the SimpleHTTPServer modules have been merged into the http.server module. So you will have to modify the above script as follows:

Change the

import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler 

to

import http.server 

(if you do this then the calls should be modified to http.server.SimpleHTTPRequest etc.)

or

from http.server import BaseHTTPServer, SimpleHTTPServer, SimpleHTTPRequestHandler 

(with this option calls remain the same as the original script)

then run the server script: python server.py


IN YOUR CASE:

You should modify the ROUTES variable to suite your needs.
For example, you want to hide the /html folder from your url:

ROUTES = (     ['', '/exact/path/to/folder/html'],     ['/another_url_path', '/exact/path/to/another/folder'],     ... ) 

Now if you hit: http://localhost:8000/index.html you will be in your home page.


Note: This script by default will serve the contained files in the folder that is in when executed to the domain url (ex. I have server.py on the Documents folder, then when I run it, http://localhost:8000 url will server my Documents folder).
You can change this behavior by the Routes (see the 'default' match comment on the code) or by placing the script in your projects root folder and start it from there.

Good luck :)

Read More

Tuesday, April 11, 2017

zf2 - Force SSL/https using .htaccess

Leave a Comment

I have followed this question and also this question But didn't helped me much.

I'm on Zend Framework2

I'm getting page is not redirecting properly error.

This is my .htaccess file,

RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$ RewriteRule ^(.*) - [E=BASE:%1] RewriteCond $1 !^(index\.php|robots\.txt|(.*).gif|(.*).jpg|(.*).png|(.*).jpeg|(.*).GIF|(.*).JPG|(.*).PNG|(.*).JPEG|upload|(.*).js|(.*).css) RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]  <IfModule mod_deflate.c> <IfModule mod_setenvif.c> <IfModule mod_headers.c> SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding </IfModule> </IfModule>  <IfModule mod_filter.c> AddOutputFilterByType DEFLATE application/atom+xml \ application/javascript \ application/json \ application/rss+xml \ application/vnd.ms-fontobject \ application/x-font-ttf \ application/x-web-app-manifest+json \ application/xhtml+xml \ application/xml \ font/opentype \ image/svg+xml \ image/x-icon \ text/css \ text/html \ text/plain \ text/x-component \ text/xml </IfModule> </IfModule>  <IfModule mod_php5.c>     #Session timeout 90 days - 7776000     php_value session.cookie_lifetime 7776000     php_value session.gc_maxlifetime 7776000 </IfModule> 

I have added this at the starting of the .htaccess file,

RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

But didn't worked for me.

What am I doing wrong?

Edit - Apache version is 2.2.15.

5 Answers

Answers 1

Try using in htaccess

RewriteCond %{HTTP_HOST} ^example.net$ [NC] RewriteRule (.*) https://www.example.net/$1 [R=301,L] 

or just add an function to your bootstrap file

    protected function _initForceSSL() {     if($_SERVER['SERVER_PORT'] != '443') {         header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);         exit();     } } 

Answers 2

Have you tried this?

RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] 

Answers 3

You can try this

#Rewrite to HTTPS RewriteCond %{HTTPS} off RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

This worked for me.

Answers 4

To force all web traffic to use HTTPS insert the following lines of code in the .htaccess file in your website’s root folder.

Important: If you have existing code in your .htacess, add this above where there are already rules with a similar starting prefix.

To force a specific domain to use HTTPS, use the following lines of code in the .htaccess file in your website's root folder:

RewriteEngine On  RewriteCond %{HTTP_HOST} ^example\.com [NC] RewriteCond %{SERVER_PORT} 80  RewriteRule ^(.*)$ https://www.example.com/$1 [R,L] 

Make sure to replace example.com with the domain name you're trying force to https. Additionally, you need to replace www.example.com with your actual domain name.

If you want to force SSL on a specific folder you can insert the code below into a .htaccess file placed in that specific folder:

RewriteEngine On  RewriteCond %{SERVER_PORT} 80  RewriteCond %{REQUEST_URI} folder  RewriteRule ^(.*)$ https://www.example.com/folder/$1 [R,L] 

Make sure you change the folder reference to the actual folder name. Then be sure to replace www.example.com/folder with your actual domain name and folder you want to force the SSL on.

Answers 5

Favori solution.

<IfModule mod_rewrite.c>     RewriteEngine On     RewriteCond %{HTTPS} off     RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]     RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]     RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L] </IfModule> 

A nice answer Best Practice: 301 Redirect HTTP to HTTPS (Standard Domain)

Read More

Wednesday, April 5, 2017

Rewrite rule for name.123456.js in htaccess

Leave a Comment

I have this file in my webserver:

http://example.com/static/js/min/common.min.js 

Since all files inside /static/ are cached with CloudFlare's Edge Cache, I need a way to change the url with something like this, so if the file is modified, the new version will be automatically fresh served:

http://example.com/static/js/min/common.min.1234567890.js 

Where 1234567890 is the timestamp of the file's date modification. I already generate the filename according to the modification date, the issue I'm having is in the .htaccess file.

This works fine:

RewriteRule ^(.*)\.[\d]{10}\.(js)$ $1.$2 [L] 

That means that:

http://example.com/static/js/min/common.min.1234567890.js 

Is redirected to:

http://example.com/static/js/min/common.min.js 

But, that will catch all .js requests from the domain, I just want to catch .js requests from within /static/js/min/*.js -- but this is failing:

RewriteRule ^static/js/min/(.*)\.[\d]{10}\.(js)$ $1.$2 [L] 

What should the rule be like?

1 Answers

Answers 1

From your question,

You want to redirect

http://example.com/static/js/min/common.min.1234567890.js 

to

http://example.com/static/js/min/common.min.js 

So, How to do that

the .htaccess

First add

 RewriteEngine On  

To turn on the rewrite engine

Then the next important line comes

RewriteRule ^static/js/min/([^\d]*)(\d{10}).js$ static/js/min/$1js [L] 

Explanation

Set the path as static/js/min/

Then we use RegEx to take the string until a non digit. ([^\d]*).

That is common.min. is captured.

Now $1 is common.min.

Then to match the url, we use (\d{10}) to capture the digits.

That is 1234567890 is captured.

Now $2 is 1234567890 which we don't want anymore

Then redirect to

static/js/min/$1js 

Not that here we didn't added the . after the $1 because $1 ending with a . (common.min.)

So, the code will be

RewriteEngine On RewriteRule ^static/js/min/([^\d]*)(\d{10}).js$ static/js/min/$1js [L] 

Working Screenshot

My File Structure

enter image description here

The Address in Browser

enter image description here

Read More

Sunday, January 29, 2017

Set urls for redirect to a specific url without rewrite

Leave a Comment

I'm building a webscheduler that have a multitenant structure, what I'm trying to do is assign a custom url that point to my application to each buyer.

So essentially when a user buy a license from me, I'll create a custom url on my webserver like this:

https://foo.scheduler.com/login 

where foo is the name of the user that has buyed the license, and scheduler is a default part of the url, another example with more buyers:

https://foo.scheduler.com/login https://foo2.scheduler.com/login https://foo3.scheduler.com/login 

essentially there are three buyers (my customers), each custom endpoint allow me to identify the correct database credentials, 'cause in my logic each tenant have a specific db, for more data organization.

Actually my application is located to this endpoint:

http://webserver/scheduler 

I want to know if is possible point all custom urls to http://webserver/scheduler, without rewrite the url in the browser, so for example when the user go to https://foo.scheduler.com/login in the true is http://webserver/scheduler/login, but the user still continue to see https://foo.scheduler.com/login.

How can do this? In my .htaccess, available inside the root of the application folder I've this content:

RewriteEngine On  RewriteBase /webscheduler/  RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l  RewriteRule ^(.+)$ index.php?url=$1 [QSA,L] 

this allow me to rewrite the base path to the index, and shunt the trace to the specific controller.

1 Answers

Answers 1

Note: I'm taking literally your statements that the app is using http:// and the clients will use https:// URLs. Also I'm assuming that the clients are hitting the same server as the one that hosts the app.


Probably the simplest way to do this is to configure one VirtualHost for your actual application and a separate one for the other URLs.

So assuming your application lives in /var/www/html/scheduler, then your existing VirtualHost looks like:

<VirtualHost *:80>    ServerName webserver    DocumentRoot "/var/www/html" </VirtualHost> 

You would need to add change your conf.d/ssl.conf to have something like:

NameVirtualHost *:443  <VirtualHost *:443>     ServerAlias *.scheduler.com     DocumentRoot "/var/www/html/scheduler" </VirtualHost> 
Read More

How to redirect multiple dynamic URLS with apache

Leave a Comment

I am trying to redirect multiple paths some with dynamic path names that can be anything.

For example:

This is the code I have now.

RewriteEngine on  RedirectMatch "^/" "http://www.bbb.ai/nl/" RedirectMatch "^/en/" "http://www.bbb.ai/en/"  RedirectMatch "^/media/" "http://www.bbb.ai/nl/media/" RedirectMatch "^/media/(.*)" "http://www.bbb.ai/nl/media/" RedirectMatch "^/en/media/" "http://www.bbb.ai/en/media/" RedirectMatch "^/en/media/(.*)" "http://www.bbb.ai/en/media/"  RedirectMatch "^/portfolio/" "http://www.bbb.ai/nl/media/" RedirectMatch "^/portfolio/(.*)" "http://www.bbb.ai/nl/media/" RedirectMatch "^/en/portfolio/" "http://www.bbb.ai/en/media/" RedirectMatch "^/en/portfolio/(.*)" "http://www.bbb.ai/en/media/"  RedirectMatch "^/team/(.*)" "http://www.bbb.ai/nl/about-us" RedirectMatch "^/en/team/(.*)" "http://www.bbb.ai/en/about-us" 

How do I achieve this?

1 Answers

Answers 1

The code in your question suggests you may be confusing two techniques of URL rewriting. RewriteEngine On provides RewriteRule functionality by mod_rewrite, but RedirectMatch is part of mod_alias.

Using either correctly should yield the correct solution for your scenario, but I will make use of RewriteRule here, so ensure that mod_rewrite is enabled on your server. I have also made an assumption that these rules are in your VirtualHost and not an .htaccess file.

RewriteEngine on  # / RewriteRule "^/$" "http://www.bbb.ai/nl/" [R,L] RewriteRule "^/team/?$" "http://www.bbb.ai/nl/about-us" [R,L] RewriteRule "^/media/.+" "http://www.bbb.ai/nl/media/" [R,L] RewriteRule "^/portfolio/.+" "http://www.bbb.ai/nl/media/" [R,L]  # /en RewriteRule "^/en/?$" "http://www.bbb.ai/en/" [R,L] RewriteRule "^/en/team/?$" "http://www.bbb.ai/en/about-us" [R,L] RewriteRule "^/en/media/.+" "http://www.bbb.ai/en/media/" [R,L] RewriteRule "^/en/portfolio/.+" "http://www.bbb.ai/en/media/" [R,L] 

At the root URLs, the end anchor $ is used to make sure that they will redirect only when nothing else is present. For media and portfolio, you state in the question that they should redirect only when followed by something dynamic.

If you actually want to redirect both /portfolio and /portfolio/something-dynamic, you can do so like:

RewriteRule "^/en/portfolio(/.*)?" "http://www.bbb.ai/en/portfolio/" [R,L] 

And given media and portfolio both have the same destination, you could actually combine as below:

RewriteRule "^/en/(media|portfolio)/.+" "http://www.bbb.ai/en/media/" [R,L] 

Though this is less code, it is also less readable, so bear that in mind when activating the rules.

Read More

Wednesday, August 24, 2016

Rewriterule .htaccess in subfolder

Leave a Comment

I need to perform a rewrite in a subfolder using the .htaccess file. The current url has a form like:

domain.com/subfolder/chapter.php?urlkey=name 

It needs to be rewritten to:

domain.com/subfolder/chapter/name 

In the subfolder I have a .htaccess file with the following code:

<IfModule mod_rewrite.c>     Options -Indexes     RewriteEngine On     RewriteBase /subfolder/      RewriteCond %{REQUEST_FILENAME} !-d      RewriteCond %{REQUEST_FILENAME}\.php -f      RewriteRule ^chapter/([a-z0-9]+)/?$ chapter.php?urlkey=$1 [L,NC,QSA] </IfModule> 

Modrewrite is enabled, but for some reason when I go to the url

domain.com/subfolder/chapter/name 

It returns the following error:

Notice: Undefined index: urlkey 

3 Answers

Answers 1

Have this code in subfolder/.htaccess:

Options -MultiViews RewriteEngine On RewriteBase /subfolder/  RewriteRule ^chapter/([\w-]+)/?$ chapter.php?urlkey=$1 [L,NC,QSA] 

Option MultiViews (see http://httpd.apache.org/docs/2.4/content-negotiation.html) is used by Apache's content negotiation module that runs before mod_rewrite and makes Apache server match extensions of files. So if /file is the URL then Apache will serve /file.html.

Also there is no need to rewrite to chapter?... you can rewrite to chapter.php?...

Answers 2

Your error is not related to htaccess rules.

Notice: Undefined Index

Happens when you try to access an array by a key that does not exist in the array.

A typical example for an Undefined Index notice would be check sample code below.

$data = array('foo' => '42', 'bar'); echo $data['spinach']; echo $data[1]; 

Both spinach and 1 do not exist in the array, causing an to be triggered.

The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists or isset:

$data = array('foo' => '42', 'bar'); if (array_key_exists('spinach', $data)) {     echo $data['spinach']; } else {     echo 'No key spinach in array'; } 

If you have code like:

<?php echo $_POST['message']; ?> <form method="post" action="">     <input type="text" name="message">     ... 

then $_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:

if ($_POST)  ..  // if the $_POST array is not empty // or if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST 

The notices above appear often when working with $_POST, $_GET or $_SESSION. For $_POST and $_GET you just have to check if the index exists or not before you use them. For $_SESSION you have to make sure you have the session started with session_start() and that the index also exists.

Answers 3

When removing RewriteBase it does working for me

put this in subfolder please check

Options -Indexes RewriteEngine On  RewriteCond %{REQUEST_FILENAME} !-d  RewriteCond %{REQUEST_FILENAME}\.php -f  RewriteRule ^chapter/([a-z0-9]+)/?$ chapter.php?url=$1 [L,NC,QSA] 

and you have to add chapter.php? instead of chapter?.

Read More

Sunday, April 24, 2016

Hiding multiple dynamically-named subdirectories with mod_rewrite in .htaccess

Leave a Comment

I am having difficulty configuring a mod_rewrite rule in my .htaccess file to hide certain subdirectories.

Input: https://example.com/hidden_sub1/hidden_sub2/additional_sub/file.php?lang=en-US

Desired output: https://example.com/en-US/additional_sub/file

I had code that allowed me to hide something if I specifically name it:

RewriteEngine On RewriteBase / RewriteCond %{THE_REQUEST} ^GET\ /hidden_sub1/hidden_sub2/ [NC] RewriteRule ^hidden_sub1/hidden_sub2/(.*) /$1 [L,R=301] RewriteRule !^hidden_sub1/hidden_sub2/ hidden_sub1/hidden_sub2%{REQUEST_URI} [L] 

However, it stopped working once I added in the following language subdirectory code:

RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/(.*) $3?lang=$1 [L,QSA] 

Besides, the name of the subdirectory is dynamic. "hidden_sub1" might be "random_name243". However, they would always be the first two subdirectories.

So how do I take out the first two randomly-named subdirectories while still keeping the language subdirectory?

I appreciate any help.

1 Answers

Answers 1

To change your url from the form

To the form :

You can use the following Rewrite rule

RewriteEngine On RewriteBase / #1)externally redirect "/hidden_sub1/hidden_sub2/foo.php?lang=bar" to "/bar/foo" RewriteCond %{THE_REQUEST} /hidden_sub1/hidden_sub2/([^.]+)\.php\?lang=(.+)\sHTTP [NC] RewriteRule ^ /%2/%1? [L,R=301] #2)internally rewrite "/bar/foo" to "/hidden_sub1/hidden_sub2/foo.php?lang=bar" RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/([^/]+)/?$ /hidden_sub1/hidden_sub2/$2.php?lang=$1 [NC,L] 

Tested on apache 2.2. and 2.4.

Read More

Wednesday, April 13, 2016

Rewrite to URL outside of Wordpress base

Leave a Comment

My wordpress blog is installed at domain.com/blog and I have a page with subpages whose structure look like domain.com/blog/page and domain.com/blog/page/subpage.

I want my visitors to be able to go to domain.com/subpage and see the content of domain.com/blog/page/subpage without being redirected to that URL externally, avoiding wordpress permalink rewrites.

I tried using RewriteRule ^subpage$ /page/subpage [L] and the content is being served, but the url looks like domain.com/blog/page/subpage (I'd guess Wordpress permalinks are getting to it.)

.htaccess:

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

EDIT:

These logs show the activity on page visit -

ip - - [19/Jun/2012:14:03:53 -0400] "GET /subpage/ HTTP/1.1" 301 - "http://domain.com/referrer/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1" ip - - [19/Jun/2012:14:03:53 -0400] "GET /blog/page/subpage/ HTTP/1.1" 200 20022 "http://domain.com/referrer/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1" 

Also, here is my root .htaccess -

<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^subpage/?$ /blog/page/subpage/ [QSA,L]  RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule>  RewriteCond %{HTTP_HOST} ^domain.com$ [OR] RewriteCond %{HTTP_HOST} ^www.domain.com$ 

1 Answers

Answers 1

Adding some rules in your htaccess, while using Wordpress, is always tricky. Instead, you should use its rewrite API.

First, put this code at then end of /wp-content/themes/CURRENT_THEME_ACTIVATED/functions.php:

function my_custom_page_rewrite_rule() {     add_rewrite_rule('^subpage/?', 'index.php?pagename=page/subpage', 'top'); } add_filter('init', 'my_custom_page_rewrite_rule'); 

Remark: you need to specify the page levels in pagename parameter, otherwise the url will change.

Then, you need to tell Wordpress it has to take your new rule into consideration. For this, go to your admin panel: Settings > Permalinks > click on Save button. Now, you should be able to go to domain.com/blog/subpage and see the content of domain.com/blog/page/subpage (the url does not change anymore).

Finally, if you want to make domain.com/subpage reachable, you need to add a htaccess in root folder and put this code into it:

RewriteEngine On RewriteBase /  RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/?$ blog/$1 [L] 

And... that's it. You can go to domain.com/subpage and now you'll get what you want.

Read More