Showing posts with label .htaccess. Show all posts
Showing posts with label .htaccess. 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, June 6, 2018

How can we include php files without specifying the subfolder path

Leave a Comment

Normally we use the following code to include php files inside each other:

<?php   include_once 'include/config.php'; // OR include 'include/config.php';  // OR  include_once $_SERVER['DOCUMENT_ROOT'].'include/config.php'; // ect... ?> 

But the above codes only apply if the php files are in the root file. I mean, if we move our files into a subfolder. We need to make a change to the code we included in the php files. For example like this:

<?php      include_once 'subfolder/include/config.php';     // OR     include 'subfolder/include/config.php';      // OR      include_once $_SERVER['DOCUMENT_ROOT'].'/subfolder/include/config.php';     // ect... ?> 

What I'm saying is that when we move our php files into the subfolder, then include_once want to see subfolder name like (include_once 'subfolder/include/config.php';). This is a challenging situation because we need to do this for the included page in many files.

For example i include the include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php'; from the index.php and also included this includes.php file from all php files like header.php, posts.php, and ajax_post.php . It is working fine from the root folder but if we move the files in the subfolder then include.php file not including without subfolder name.

Maybe it is also possible to do this with .htaccess.

I have made this htaccess code maybe you have a solution with htaccess. I must be say i have tryed to use RewriteBase /subfoldername/ but include files didn't worked.

Options +FollowSymLinks -MultiViews RewriteEngine On  RewriteBase /  RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC] RewriteRule ^ /%1 [R=302,NE,L]  RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{THE_REQUEST} /index\.php [NC] RewriteRule ^(.*)index\.php$ /$1 [L,R=302,NC,NE]  RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ - [L]  RewriteRule ^group/([\w-]+)/?$ sources/group.php?group_username=$1 [L,QSA]   RewriteRule ^profile/([\w-]+)/?$ sources/user_profile.php?username=$1 [L,QSA] RewriteRule ^profile/(followers|friends|photos|videos|locations|musics)/([\w-]+)/?$ sources/$1.php?username=$2 [L,QSA]       RewriteRule ^admin/(.*)$ admin/index.php?page=$1 [L,QSA]  RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.+?)/?$ $1.php [L]    RewriteRule ^(.+?)/?$ index.php?pages=$1 [L,QSA] 

. My responsibility is, how can we include php files without subfolder name?

9 Answers

Answers 1

You can use auto_prepend_file directive in your .htaccess to make a .php file included before all of your php files.

Have this in your .htaccess:

php_value auto_prepend_file "/Applications/MAMP/htdocs/script/env.php" 

Then create a new file env.php in your project base directory with just one line:

<?php    $baseDir = __dir__ . '/'; ?> 

This line sets a variable $baseDir that has value of your project base directory i.e. /Applications/MAMP/htdocs/script/ OR /Applications/MAMP/htdocs/subdir/script/

Then use this variable $baseDir anywhere you have to include other files such as:

include_once $baseDir.'functions/includes.php';  include_once $baseDir.'functions/get.php'; 

Answers 2

__DIR__ is certainly what you are looking for. Use it to provide relative paths for required files. I would highly suggest using require_once or include_once for all library files.

include_once dirname(dirname(__DIR__))."/include/config.php"; 

Answers 3

You have to use function set_include_path() and somewhere in your bootstrap.php or index.php add next code:

<?php $path = '/usr/pathToYourDir'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); 

now everywhere below you can write this:

include_once 'include/config.php'; // or include_once 'include/db/index.php'; // etc 

And in case you need to move your code into another directory - you have only to change value of path varibalbe $path = '/usr/pathToYourDir'; to new path to your directory.

Answers 4

Ok, I'm not a fan of doing this, but it will get the job done, as requested:

$newpath="";  $dirs = array_filter(glob('*'), 'is_dir'); foreach ($dirs as $location) {     $newpath .= PATH_SEPARATOR . $location;  } set_include_path(get_include_path() . $newpath); 

The above code will find all subfolders from where this file is running, and add them all to the current include path. by changing the glob from:

glob('*')  

to

glob('includes/*')  or glob('includes' . DIRECTORY_SEPARATOR . '*') 

You can restrict it to only subfolders under includes.

The above is not tested, I just threw the code together, but it illustrates a way to do what you're asking for.

I would still recommend putting files in determined locations rather than trying to include them from anywhere.

Answers 5

This is how I would do it.

//----- some global location like index.php  if(!defined("CONFIG_PATH")) define("PATH_CONFIG", __DIR__."/include/");  //------------ then later in some other file  if(!defined("CONFIG_PATH"))die("Config path is not defined.");  include_once CONFIG_PATH.'config.php'; 

Then when you change it you just update

if(!defined("CONFIG_PATH")) define("PATH_CONFIG", __DIR__."/include/subfolder/"); 

I would say this is the "Traditional" way to do it, and it's perfectly fine to use a global constant for this. It's not something you want changing at run time. You need access to it in many places, potentially. You can check if your files are accessed properly .. etc.

Many many many, MVC frameworks do it this exact way.

Answers 6

Refer this link hope it helps http://www.geeksengine.com/article/php-include-path.html

Answers 7

Here's an example of an approach that requires your files upfront via the auto_prepend_file directive.

bootstrap.php:

<?php  $require_upfront = function($dir) {     require_once $dir . '/one.php';     require_once $dir . '/two.php'; };  $require_upfront(__DIR__ . '/inc'); 

Add to php config, here .htaccess example:

php_value auto_prepend_file "/abs/path/to/bootstrap.php" 

Answers 8

If you have the file's name unique in all server, you can make a research of this using a research like this.

I think that this solution isn't better when this script run a lot of, but you can include if the include function fails, using try and catch (if you use this method watch the php version) or if you know that this path change once a day you can make a file which is launched with routine.

If you make this, you need to store this path, but I don't know if there is a method for make global variable. My solution is to store or in a DB or in a file.

I hope I have helped you.

Answers 9

Using Apache to fix your app is solving it at the wrong level.

If you have to update a bunch of files in your code when the location of a file changes, that is your code telling you that you have made a bad architectural decision. So fix the actual problem and stop repeating yourself.

Define where your includes live in one place, and then when needed, update that one place accordingly.

One way to do this is set a constant at the root of your app. This assumes you have a bit of code at the root of your app that is called on every page. This would likely be index.php or a script included by index.php:

// index.php or a file included by index.php const MY_INCLUDE_PATH = __DIR__ . '/path/to/subfolder` 

Then your other scripts can call include using the constant:

// some other script included to handle the page include MY_INCLUDE_PATH . '/config.php'; include MY_INCLUDE_PATH . '/some-other-include.php'; 

Although if they all want to include the config.php file, maybe just go ahead and include it in your index.php.

This is not a "bad" global you want to avoid. It is using constants as they are intended. Constants are part of the namespace, if you are using a namespace for your app.

This assumes there is one include subfolder that sometimes changes places and a script somewhere that is a part of every request. Is that correct? If not, please post your directory structure.

A function would also work, and could include logic based on things such as the path of the calling script:

// index.php or a file included by index.php my_include_function($path) {   //do stuff } 

The other scripts might call this function like so:

// some other script included to handle the request my_include_function(__FILE__); 

Then when things change, you simply update one function in one file.

This all assumes you have an index.php or similar script that handles every request and can be the single point of control for defining the function or constant. If that's not the case, it should be!

Updating your code to use a router (here is one) would take maybe 10 minutes and potentially simplify that gnarly .htaccess file you posted.

Read More

Remove multiple trailing slashes in root using htaccess

Leave a Comment

I have a rule in my htaccess file to remove any extra trailing slashes from a url, this works on sub-directories with any more than 1 trailing slash. However it doesn't work on the root; which i need it to do.

For example.

http://www.example.com/test//// Redirects to http://www.example.com/test/

http://www.example.com/// Needs to redirect to http://www.example.com

Any ideas on what i need to add?. Cheers.

RewriteCond %{REQUEST_URI} ^(.*?)(?:/){2,}$ RewriteRule . %1/ [R=301,L] 

4 Answers

Answers 1

Try with:

RewriteCond %{REQUEST_URI} ^(.*?)//+$ RewriteRule ^ %1/ [R=301,L] 

Answers 2

For removing multiple slashes anywhere in REQUEST_URI this rule works best:

RewriteEngine On  RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule ^.*$ /$0 [R=301,L,NE] 

It takes advantage of the fact that mod_rewrite engine itself converts all multiple forward slashes to a single slash in the RewriteRule pattern. We use RewriteCond %{THE_REQUEST} to make sure original REQUEST_URI contains multiple slashes.

Answers 3

You just need two rule to match two different pattern

RewriteCond %{REQUEST_URI} ^(?:/){2,}$ RewriteRule . / [R=301,L]  RewriteCond %{REQUEST_URI} ^(.*?)(?:/){2,}$ RewriteRule . %1/ [R=301,L] 

Answers 4

You htaccess works great as you can test on below link

https://htaccess.madewithlove.be/

Working

So you need to make sure you test either with a Chrome Incognito window or using like below

curl -v http://example.com//// 

I usually prefer curl as I know it will give a fresh response from the server always

Read More

Monday, April 9, 2018

Htaccess - Skip redirect if env var is not set

Leave a Comment

I simply want to skip a redirect done with a "RewriteRule" when a specific env variable is not set by a former "RewriteRule".

Here is my example which doesn't work.

RewriteEngine on RewriteBase /  # # if /internal ... set ENV var INTERNALAREA = true # RewriteRule ^internal(.*)$ - [E=INTERNALAREA:true]  # # Redirect to /maintenance.php if not in internal area and not already at /maintenance.php # RewriteCond %{ENV:INTERNALAREA} !true RewriteCond %{REQUEST_URI} !^/maintenance.php$ RewriteRule ^(.*)$ /maintenance.php [R=302,L]  # # Default TYPO3 rewrites # RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)\.(\d+)\.(php|js|css|png|jpg|gif|gzip)$ $1.$3 [L]  RewriteRule ^fileadmin/(.*/)?_recycler_/ - [F] RewriteRule ^fileadmin/templates/.*(\.txt|\.ts)$ - [F] RewriteRule ^typo3conf/ext/[^/]+/Resources/Private/ - [F] RewriteRule ^(typo3/|t3lib/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon\.ico) - [L]  RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule .* index.php [L] 

In the maintenance PHP I have a phpinfo() which outputs $_SERVER['REDIRECT_REDIRECT_INTERNALAREA'] = true.

I'm always getting redirected to the maintenance.php when accessing /internal/....

What am I doing wrong?

1 Answers

Answers 1

I have found the answer to my question. The problem has its roots at the following question:

When setting environment variables in Apache RewriteRule directives, what causes the variable name to be prefixed with "REDIRECT_"?

When now setting the following before all the other rules everything does work as expected:

RewriteCond %{ENV:REDIRECT_INTERNALAREA} (.+) RewriteRule .* - [E=INTERNALAREA:%1] 

What it does it checks on every run if prefixed the prefixed env var is already set and re adds the environment variable without the REDIRECT_ prefix.

Read More

Thursday, March 22, 2018

htaccess header for specific domain?

Leave a Comment

I have three environments:

env.com env-uat.com env-pre.com 

All three pages run the same code. I want env-uat.com and env-pre.com to both get this in the htaccess:

Header set X-Robots-Tag "noindex, nofollow" 

This will effectively completely unindex these pages, including PDF files etc. But I don't want to affect env.com.

How can I make the Header X-Robots-Tag only be added for env-uat.com and env-pre.com and NOT env.com?

** UPDATE **

From what I could find so far, it would seem you can only do something like this:

SetEnvIf Request_URI "^/privacy-policy" NOINDEXFOLLOW Header set X-Robots-Tag "noindex, follow" env=REDIRECT_NOINDEXFOLLOW 

But this makes it specific to a PAGE. I want it specific to a DOMAIN.

2 Answers

Answers 1

@Starkeen was right up to here :

SetEnvIf host ^(env-uat\.com|host2\.com)$ NOINDEXFOLLOW 

So , you could include the domains that you want to be involved in this Env like this :

SetEnvIf host ^(env-uat|env-pre)\.com NOINDEXFOLLOW 

Then you should attach the Env with same name like this :

Header set X-Robots-Tag "noindex, follow" env=NOINDEXFOLLOW 

Not like this :

Header set X-Robots-Tag "noindex, follow" env=REDIRECT_NOINDEXFOLLOW 

The line above will look to Env its name is REDIRECT_NOINDEXFOLLOW not NOINDEXFOLLOW and it is diffrent case from this question X Robots Tag noindex specific page That was about matching against Request_URI and for special case .

So , the code should look like this :

SetEnvIf host ^(env-uat|env-pre)\.com NOINDEXFOLLOW Header set X-Robots-Tag "noindex, follow" env=NOINDEXFOLLOW 

Answers 2

You can match against Host header using SetEnvIf directive.

To make the Header X-Robots-Tag only available for a specific host ( env-uat.com ) you could use something like the following :

SetEnvIf host ^env-uat\.com$ NOINDEXFOLLOW Header set X-Robots-Tag "noindex, follow" env=REDIRECT_NOINDEXFOLLOW 

To make this available for multiple hosts ,you could use the following :

SetEnvIf host ^(env-uat\.com|host2\.com)$ NOINDEXFOLLOW Header set X-Robots-Tag "noindex, follow" env=REDIRECT_NOINDEXFOLLOW 
Read More

Wednesday, March 7, 2018

Serve content from external server via apache

Leave a Comment

I am running my web app at abc.com with apache as the web server.

I have some static pages hosted on SquareSpace... eg. abc.squarespace.com/landing

I want to configure apache to serve content from abc.squarespace.com when it get's a request for abc.com/landing

I've done this in nginx by using proxy_pass with the backend as abc.squarespace.com for location /landing. But I'm not sure how to do this in Apache. No luck doing research on the web as well.

Thanks in advance.

1 Answers

Answers 1

Message body cannot contain URLs with abc.com, so I will be using example.com and example.squarespace.com.

I believe you are looking for frame forwarding. In order to implement it, use the following steps:

  1. On example.squarespace.com allow frame forwarding from example.com by setting the appropriate HTTP headers via web server configuration:

X-Frame-Options: ALLOW-FROM https://example.com/

For detailed explanation refer to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

  1. Verify that Apache mod_proxy_http is enabled at example.com:

# apachectl -M | grep proxy_http proxy_http_module (shared)

  1. Set the following rewrite rules in Apache configuration or .htaccess file to serve content from http://example.squarespace.com/landing

<IfModule proxy_http_module> RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC] RewriteRule ^landing(.*) http://example.squarespace.com/landing [P] </IfModule>

The syntax here is the same as for Apache mod_rewrite.

Read More

Monday, February 5, 2018

how to Remove Sub directory name from URL with htaccess?

Leave a Comment

My URL was

http://demo.example.com/parentFolder/

but i have to redirect it to child folder, URL as

http://demo.example.com/parentFolder/ChildFolder/

i have redirect it in htaccess as

<IfModule mod_rewrite.c>         RewriteEngine On        RewriteCond %{HTTP_HOST} ^(www.)?demo.example.com/parentFolder$        RewriteCond %{REQUEST_URI} !^/ChildFolder/          RewriteCond %{REQUEST_FILENAME} !-f        RewriteCond %{REQUEST_FILENAME} !-d         RewriteRule ^(.*)$ /ChildFolder/$1         #RewriteCond %{HTTP_HOST} ^(www.)?demo.example.com/parentFolder$        RewriteRule ^(/)?$ ChildFolder/ [L]  </IfModule> 

but didn't remove sub folder(ChildFolder) from URL. i want to access childFolder after redirect but want to hide childFolder from URL.

1 Answers

Answers 1

You can use these rule in parentFolder/.htaccess:

RewriteEngine On  # remove ChildFolder from URL show in browser RewriteCond %{THE_REQUEST} \s/+(parentFolder)/ChildFolder/(\S*)\s [NC] RewriteRule ^ /%1/%2 [R=301,NE,L]  # add ChildFolder internally  RewriteRule ^$ ChildFolder/ [L]  RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(?!ChildFolder/).*$ ChildFolder/$0 [L,NC] 
Read More

Thursday, February 1, 2018

Force Heroku PHP app to use https for both www and non-www versions

Leave a Comment

I have a PHP app on Heroku with an SSL certificate for the www version of the domain name. I need all requests (to both www and non-www) to go to via https, and I have added .htaccess to that affect. However, there are still circumstances where it's possible for a user to access the http version and I don't understand why.

Here is my .htaccess:

RewriteEngine on  RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$ RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R] 

My understanding is that this should force all users to access via https://www, but that doesn't always happen. For example, Google sometimes provides search results without the https and the links open insecure http instead.

Any ideas about what I'm doing wrong?

2 Answers

Answers 1

first redirect to the same host-name on :443, then redirect to www.. ordinary www. is just an alias in DNS, while most use the shorter non-www hostname for websites. you might have to extend the certificate, because it requires both host-names explicitly added, unless it's wild-carded.

one does not have to filter for the host-name:

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

also see this answer here, concerning robots.txt with enforced SSL.

Answers 2

Try the following rules and let me know if it works or not these rule will use https request instead of http or www and non-www version. The following rule will now redirect the user to the something like this.

https://www.example.com/

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

Hope this will help to achieve what you wanted

Read More

Tuesday, January 9, 2018

Remote access of WAMP redirects to duplicate url

Leave a Comment

When I access WordPress website from remote device on local network ie: www.test.local WAMP decides to redirect this request to url which looks like www.test.localhttp/www.test.local/ And I will get an error. However when I access the url from the main computer(with WAMP) redirect does not occur. I tried to remove main wordpress htaccess. If the website has only index.html this problem does not occur.

All I get from error log:

[www.test.local/sid#1a426ce7a18][rid#1a432dc9390/initial] [perdir C:/Users/{MyUser}/work/test/www/] strip per-dir prefix: C:/Users/{MyUser}/work/test/www/ ->  [www.test.local/sid#1a426ce7a18][rid#1a432dc9390/initial] [perdir C:/Users/{MyUser}/work/test/www/] applying pattern '^index\\.php$' to uri '' [www.test.local/sid#1a426ce7a18][rid#1a432dc9390/initial] [perdir C:/Users/{MyUser}/work/test/www/] strip per-dir prefix: C:/Users/{MyUser}/work/test/www/ ->  [www.test.local/sid#1a426ce7a18][rid#1a432dc9390/initial] [perdir C:/Users/{MyUser}/work/test/www/] applying pattern '.' to uri '' [www.test.local/sid#1a426ce7a18][rid#1a432dc9390/initial] [perdir C:/Users/{MyUser}/work/test/www/] pass through C:/Users/{MyUser}/work/test/www/ [www.test.local/sid#1a426ce7a18][rid#1a4296ec5d0/subreq] [perdir C:/Users/{MyUser}/work/test/www/] strip per-dir prefix: C:/Users/{MyUser}/work/test/www/index.php -> index.php [www.test.local/sid#1a426ce7a18][rid#1a4296ec5d0/subreq] [perdir C:/Users/{MyUser}/work/test/www/] applying pattern '^index\\.php$' to uri 'index.php' [www.test.local/sid#1a426ce7a18][rid#1a4296ec5d0/subreq] [perdir C:/Users/{MyUser}/work/test/www/] pass through C:/Users/{MyUser}/work/test/www/index.php [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] add path info postfix: C:/Users/{MyUser}/work/test/www/www.test.local -> C:/Users/{MyUser}/work/test/www/www.test.local/ [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] strip per-dir prefix: C:/Users/{MyUser}/work/test/www/www.test.local/ -> www.test.local/ [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] applying pattern '^index\\.php$' to uri 'www.test.local/' [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] add path info postfix: C:/Users/{MyUser}/work/test/www/www.test.local -> C:/Users/{MyUser}/work/test/www/www.test.local/ [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] strip per-dir prefix: C:/Users/{MyUser}/work/test/www/www.test.local/ -> www.test.local/ [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] applying pattern '.' to uri 'www.test.local/' [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] RewriteCond: input='C:/Users/{MyUser}/work/test/www/www.test.local' pattern='!-f' => matched [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] RewriteCond: input='C:/Users/{MyUser}/work/test/www/www.test.local' pattern='!-d' => matched [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] rewrite 'www.test.local/' -> '/index.php' [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] trying to replace prefix C:/Users/{MyUser}/work/test/www/ with / [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] trying to replace context docroot c:/Users/{MyUser}/work/test/www with context prefix  [www.test.localhttp/sid#1a426ce7a18][rid#1a4334b9cc0/initial] [perdir C:/Users/{MyUser}/work/test/www/] internal redirect with /index.php [INTERNAL REDIRECT] [www.test.localhttp/sid#1a426ce7a18][rid#1a4334a4b68/initial/redir#1] [perdir C:/Users/{MyUser}/work/test/www/] strip per-dir prefix: C:/Users/{MyUser}/work/test/www/index.php -> index.php [www.test.localhttp/sid#1a426ce7a18][rid#1a4334a4b68/initial/redir#1] [perdir C:/Users/{MyUser}/work/test/www/] applying pattern '^index\\.php$' to uri 'index.php' [www.test.localhttp/sid#1a426ce7a18][rid#1a4334a4b68/initial/redir#1] [perdir C:/Users/{MyUser}/work/test/www/] pass through C:/Users/{MyUser}/work/test/www/index.php [www.test.localhttphttp/sid#1a426ce7a18][rid#1a4426f31f0/initial] [perdir C:/Users/{MyUser}/work/test/www/] add path info postfix: C:/Users/{MyUser}/work/test/www/www.test.localhttp -> C:/Users/{MyUser}/work/test/www/www.test.localhttp/www.test.local/ [www.test.localhttphttp/sid#1a426ce7a18][rid#1a4426f31f0/initial] [perdir C:/Users/{MyUser}/work/test/www/] strip per-dir prefix: C:/Users/{MyUser}/work/test/www/www.test.localhttp/www.test.local/ -> www.test.localhttp/www.test.local/ 

My vhosts file:

<VirtualHost *:80>  ServerName localhost2.local  ServerAlias *.*.local  VirtualDocumentRoot "c:/Users/{MyUser}/work/%2/%1/"  <Directory "c:/Users/{MyUser}/work/">   ServerSignature Off   Options Indexes FollowSymLinks IncludesNoExec   AllowOverride All   Order allow,deny   Allow from all   # Insert the following:   Require all granted  </Directory> </VirtualHost> 

If I will use standard WP generated .htaccess :

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

The results is that the URL is redirected to www.test.localhttphttphttp... etc until the limit is reached... On the remote device is WAMP pc IP as a proxy. Any idea where could the redirect be originating?

EDIT: Updated log - this is what shows rewrite tracing. When accessing from localhost machine it is the same up until the line 9 and then it just calls assets etc as usual...

3 Answers

Answers 1

EDIT: This doesn't seem to be the problem, as the updates to the question make clear. Still leaving this here for random googlers that may find it useful.

To update your wordpress site's URL:

You can update the option_name's 'home' and 'siteurl' to option_value's of 'http://www.test.local/' (same value for both) in your wp_options table -

     UPDATE [yourWPDB].wp_options      SET option_value='http://www.test.local/'      WHERE option_name = 'home' OR option_name = 'siteurl' 

You can also add the following lines to your wp-config.php file in your wordpress root to update -

     define('WP_SITEURL', 'http://www.test.local/');      define('WP_HOME', 'http://www.test.local/'); 

Answers 2

You have to update your site url and domain name on the wordpress configuration. This is saved as a serialized data in a table that I do not remember the name.

The easiest fix is edit index.php and at the end add:

update_option( 'siteurl', 'http://www.test.local' ); update_option( 'home', 'http://www.test.local' ); 

Open your site this will update your wordpress configuration. Then you can delete those lines and leave the index.php as it was.

Clear your browser cache or use the incognito mode and open www.test.local

Answers 3

try updating options values 'siteurl'=>'http://www.test.local' ); 'home'=>'http://www.test.local' from database (wp_options) table and dont put trailing slash at the end of the url.. e.g. www.test.local/..reset permalink from backend as well

Read More

Friday, December 22, 2017

Included php files wont work after moved files subfolder

Leave a Comment

I have a problem with php include section. In order to fully explain the problem, I created a test page for you.

First I want to show the schema of the files to you. Also you can download the test files from this LINK and you can test it online TEST LINK

enter image description here

As you can see, there is a subfolder in the htdocs (root) file and all php files in there. Now I'll show you the php code within the file, respectively.

appname/index.php

<?php include_once 'includes/config.php';?> <div class="callPage">Click Here</div> <div id="testBox"></div>  <script type="text/javascript">   $(document).ready(function(){       var siteurl = '<?php echo $url;?>';       $("body").on("click",".callPage", function(){        $.ajax({             url: siteurl+'content/test',             beforeSend: function() {                 //Do something             },             complete:function(){               //Do something              },             success:function(response){                 $("#testBox").html(response);             }             });     });      function LoadPage(){        $.get(siteurl+'content/test', function(data) {           $('#testBox').html(data);        });     }     LoadPage();    }); </script>   

appname/content/test.php

<?php  include_once 'includes/config.php'; echo $text.'</br>'; echo $worked.'</br>'; ?> 

appname/includes/config.php

<?php  $url = 'http://localhost:8888/'; $text = 'Well Come! How are you today ?'; $worked = 'It is working :)'; ?> 

When you open the TEST LINK, LoadPage(); javascript function will call test.php in the content file and display it in #testBox. First you will not see anything in #testBox from index.php . Because config.php can not be included from test.php .

I know if I change this line include_once 'includes/config.php'; from test.php like this include_once '/appname/includes/config.php'; then problem will be fix.

But if the pages multiply and, I want to use the files in the root (htdocs or www) folder, I need to delete appname (subfolder name) => include_once 'appname/includes/config.php'; from all files. It will be a big problem when these files multiply.

Actually the question is exactly:

How can we include php files without specifying the full path to the include, when the application's path relative to the DOCUMENT_ROOT is variable or unknown and include_path cannot be reliably modified by all application users?

5 Answers

Answers 1

This is sometimes a problem with includes when you're not using the absolute path on the system.

Explanation

Depending on how PHP is running could affect the way include&require work, if PHP is running from inside the appname directory it will work fine if php is told it's running inside the appname directory via a connector it's fine. however, if PHP is run for example www-data@/usr/bin/# php /var/www/somesite.com/htdocs/appname/index.php the path can be broken.

Fix

if you use define("FS_ROOT", realpath(dirname(__FILE__))); as the first thing other than if ther is a namespace inside index.php you can then use include FS_ROOT."/includes/config.php"; this means file paths are used from the root of the system so it gets evaluated to include "/var/www/somesite.com/htdocs/appname/index.php"

Why this differs

This differs from ROOT_PATH as ROOT_PATH is sometimes set by PHP configuration by web hosts and this could be the problem. as the PHP execution path could be wrong casing the PHP host application to look in the wrong place for includes and requries.

This also means no include or require should ever be using ../ as you should know the path from your codebase.

your appname/index.php

<?php define("FS_ROOT", realpath(dirname(__FILE__))); include_once FS_ROOT.'includes/config.php';?> <div class="callPage">Click Here</div> <div id="testBox"></div>  <script type="text/javascript">   $(document).ready(function(){       var siteurl = '<?php echo $url;?>';       $("body").on("click",".callPage", function(){        $.ajax({             url: siteurl+'content/test',             beforeSend: function() {                 //Do something             },             complete:function(){               //Do something              },             success:function(response){                 $("#testBox").html(response);             }             });     });      function LoadPage(){        $.get(siteurl+'content/test', function(data) {           $('#testBox').html(data);        });     }     LoadPage();    }); </script> 

your appname/content/test.php

<?php  # as this file is loaded directly and is not in the root directory # we apend the dirname result with ../ so realpath can resolve the root directory for this site define("FS_ROOT", realpath(dirname(__FILE__)."../")); include_once FS_ROOT.'includes/config.php'; echo $text.'</br>'; echo $worked.'</br>'; ?> 

Ideally, you should go through a bootstrap and .htaccess so you don't have to change redefine the FS_ROOT in every file loaded.

you can do this by making sure mod_rewrite is enabled in apache

create file .htaccess in appname folder

RewriteCond %{REQUEST_URI} \.(php)$ RewriteRule .* bootstap.php [L] 

create bootstrap.php

define("FS_ROOT", realpath(dirname(__FILE__))); include_once FS_ROOT.'includes/config.php'; if(file_exists(FS_ROOT.$_SERVER['REQUEST_URI']){     include(FS_ROOT.$_SERVER['REQUEST_URI']); }else{     // 404 } 

this means you don't require the include for the config as it's automaticly included before the script for that request is wanted this is just a base outline and is not 100% secure i would recomended reading up on how to use MVC's and how they work it will give you a better understanding of loading files on demand and requiring files.

Answers 2

If the document file paths need to be dynamic you need to use a database. From what I understand you are planning to make the project bigger, and so you need a normalized database to minimize the amount of code written on the server and to keep your data consistent.

You need:

  • a parent table for filePaths
  • a parent table for fileNames
  • a parent table for akas <== This is because files may have same name in different folders
  • a parent table for folders
  • a mapping table to solve the akas-fileNames-filePaths-folders relationships.

I will show on an example from MySQLi.

With this code you create the tables in MySQL console or phpmyadmin:

// Create parent tables create table `fileNames`  (     `fileName` VARCHAR(70) NOT NULL,     `description` VARCHAR(250) NULL,     PRIMARY KEY(`fileName`) ) ENGINE=InnoDB;  create table `fileAkas`  (     `aka` VARCHAR(100) NOT NULL,     `description` VARCHAR(250) NULL,     PRIMARY KEY(`aka`) )  ENGINE=InnoDB;  create table `filePaths`  (     `filePath` VARCHAR(250) NOT NULL,     `description` VARCHAR(250) NULL,     PRIMARY KEY(`filePath`) )  ENGINE=InnoDB;  create table `folderNames`  (     `folderName` VARCHAR(250) NOT NULL,     `description` VARCHAR(250) NULL,     PRIMARY KEY(`folderName`) )  ENGINE=InnoDB;  // Create mapping table create table `fileNames_x_fileAkas_x_filePaths_x_folderNames` (     `aka` VARCHAR(100) NOT NULL,     `fileName` VARCHAR(70) NOT NULL,     `filePath` VARCHAR(250) NOT NULL,     `folderName` VARCHAR(250) NOT NULL,     PRIMARY KEY (`aka`, `fileName`, `filePath`, `folderName`),     FOREIGN KEY (`aka`) REFERENCES `fileAkas` (`aka`) ON UPDATE CASCADE,     FOREIGN KEY (`fileName`) REFERENCES `fileNames` (`fileName`) ON UPDATE CASCADE,     FOREIGN KEY (`filePath`) REFERENCES `filePaths` (`filePath`) ON UPDATE CASCADE,     FOREIGN KEY (`folderName`) REFERENCES `folderNames` (`folderName`) ON UPDATE CASCADE ) ENGINE=InnoDB; 

While this piece of code is only to make sure you are not making MyISAM tables because MyISAM doesn't have relationship constraints:

ENGINE=InnoDB 

Now make a PHP program to easily add/change the data. Use this as a separate program and upload it to the server only when you need it:

<?php     // Database connection     $con = mysqli_connect("localhost","my_user","my_password","my_db");      // Function helper     function testIfAddedAndInsert($colName, $tableName, $value, $con)     {         $result = mysqli_query($con, "SELECT ".$colName." FROM ".$tableName." WHERE ".$colName."='".$value."'");         if(mysqli_num_rows($result) == 0)             mysqli_query($con, "INSERT INTO ".$tableName." (".$colName.") VALUES ('".$value."')");     }      // Call this to add new file     function addNewFile($name, $aka, $path, $folderName, $con)     {          testIfAddedAndInsert('fileName', 'fileNames', $name, $con);          testIfAddedAndInsert('fileAka', 'fileAkas', $aka, $con);          testIfAddedAndInsert('filePath', 'filePaths', $path, $con);          testIfAddedAndInsert('folderName', 'folderNames', $folderName, $con);     }      // Call this to change a file path     function changeFilePath($aka, $path, $con)     {          testIfAddedAndInsert('filePath', 'filePaths', $path, $con));          mysqli_query($con, "UPDATE `fileNames_x_fileAkas_x_filePaths_x_folderNames` SET `filePath`= '".$path."' WHERE `fileAka`='".$fileAka."' ");     }      // Call this to change all paths of all files that belong to a certain folder     function changeFolderPath($folderName, $path, $con)     {          testIfAddedAndInsert('folderPath', 'folderPaths', $folderPath, $con))              mysqli_query($con, "INSERT INTO `folderPaths` (`folderPath`) VALUES ('".$folderPath."')");          mysqli_query($con, "UPDATE `fileNames_x_fileAkas_x_filePaths_x_folderNames` SET `filePath`= '".$path."' WHERE `folderName`='".$folderName."' ");     }      // ...      // You can make as many different functions as you want      // To populate/change the database example:      addNewFile('config.php', 'conf_PHP_IndexPage', './../conf/', 'conf', $con);      // or change all the paths of the items in the folder (not counting subfolder items)     changeFolderPath('conf', './../../../', $con);      // You could use FOR loops with arrays to enter/change big chunks at a time ?> 

Then, after populating your database with valid information, add this to every one of your main PHP files (the files that are including others):

<?php     // Database connection     $con = mysqli_connect("localhost","my_user","my_password","my_db");      // Function returns path of file from database     function returnPathToFile($fileAka, $con)     {         $result = mysqli_query($con, "SELECT fileName, filePath FROM fileNames_x_fileAkas_x_filePaths_x_folderNames WHERE fileAka='".$fileAka."'");         if(mysqli_num_rows($result) > 0)         {             $row = mysqli_fetch_array($result);             return $row[1].$row[0];         }         return '';     } ?> 

And then just call the function to get the result:

<?php     $include = returnPathToFile('configFileForTheMainPage', $con);     include_once($include); ?> 

If any changes occur to the file paths it is easy to change their values, while not having to ever even open the files ever again (for that purpose).

Answers 3

The ROOT_PATH definition is OK. You could include the path after the definition like:

include ROOT_PATH; 

Answers 4

You could use namespaces with PSR. That way you only have to know the top directory. Namespaces aren't tied to the directory stucture. By using PSR you files all files are loaded on call under a base namespace and where called using

use Base\Child 

they are called and loaded. If you want to echo something out like you would with an include or require just store it in a function to be called from the namespace like this Base\Child\Function().

Answers 5

The Test.php is in content folder. If you want to include config.php from includes folder, you must need to do it relatively, so you need to go one level upper.

include '../include/config.php'; 

This happening because you run the script standalone with ajax, and the folder structure is relative to the test.php.

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

Saturday, December 2, 2017

htaccess Rewrite Rule effecting non visible links

Leave a Comment

I have a Joomla based website and I use .htaccess to redirect non www,https urls to www,https versions using the rule below:

RewriteEngine on RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule (.*) https://www.example.com%{REQUEST_URI} [R=301,L]

Each article has facebook comments code added manually which points to old non ssl urls:

<div class="fb-comments" data-href="http://www.example.com/links/main_folder/sub_folder/" data-width="625" data-numposts="5" data-colorscheme="light" data-order-by="reverse_time"></div> 

Everything was working fine however recently I noted that even the links from Facebooks data-href start redirecting to https which results in losing of old comments.

My questions is how can I modifiy the rule which does not effect links from data-href, there is a diference between old urls structure compared to new ones the old ones uses underscores and new ones hyphens if it helps. Is there a way to excplude links with underscores from this rule? How ever I have pictures that uses underscores also which I do not want to redriect.

1 Answers

Answers 1

If it's only without underscores, you can use:

RewriteEngine on RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteCond %{REQUEST_URI} !_ RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L] 
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, November 3, 2017

Wordpress and CI rewrite rule in htaccess

Leave a Comment

I have installed WordPress in example.com. I have also installed CodeIgniter in ci folder here example.com/ci/, ci is the folder name , register is the controller name and working URL of CI is example.com/ci/register .

Now I have one WordPress URL example.com/hotel, hotel is the page that I have created in WordPress admin, it works fine.

I want to run my CI path like example.com/hotel/ci/register, I think we can do it with some rewrite rule so that my URL would look like example.com/hotel/ci/register. I have added given htaccess for wordpress that redirecting me here example.com/hotel/ci/register. It is showing me 404 error of CI. It means now I am in CI. Now I did following things in routes.php file.

$route['default_controller'] = 'register'; $route['404_override'] = 'register'; 

Now this URL example.com/hotel/ci/register is working, but this is not right way, next time there will be more controllers then it will not work.

Note: I can not create hotel folder because hotel is a page in the WordPress. If I create hotel folder then WordPress URL example.com/hotel/ will not work. It will redirect WordPress page to the hotel folder. So I have to do it without creating hotel folder.

I need to find another good solution.Any advise or guidance would be greatly appreciated?

Following is my reWrite rule in wordpress htaccess:

# BEGIN WordPress    <IfModule mod_rewrite.c>     RewriteEngine On     RewriteBase /     RewriteRule ^/?hotel/ci/register(/.*)?$ /ci/$1 [L]     RewriteRule ^index\.php$ - [L]     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule . /index.php [L]     </IfModule> # END WordPress 

And following is my CI htaccess:

<IfModule mod_rewrite.c> RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L,QSA]  </IfModule> 

1 Answers

Answers 1

I think you are on the right path, try this:

# BEGIN WordPress    <IfModule mod_rewrite.c>     RewriteEngine On     RewriteBase /     RewriteRule ^/hotel/ci(/.*)?$ /ci/$1 [L]  # remove the register part                                                # so that it would be handled by CI                                               # also remove the "?" in front of hotel     RewriteRule ^index\.php$ - [L]     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule . /index.php [L]     </IfModule> # END WordPress 

keep your CI htaccess as it is:

<IfModule mod_rewrite.c> RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L,QSA]  </IfModule> 

the last part is match your CI config.php to your new url model

$config['base_url'] = "http://example.com/hotel/ci/"; 
Read More

Sunday, October 29, 2017

htaccess if URL contains string redirect to page without changing URL

Leave a Comment

I have a URL like example.com/product-name.html.

I want to redirect any URLs that contain the string html to search.php but I want to keep the original URL that was typed in, so if example.com/product-name.html was redirected to search.php it should still show example.com/product-name.html in the browser.

I am using:

RewriteCond %{REQUEST_URI} html RewriteRule .* search.php 

Which redirects but does not keep the original typed URL in the browser.

How can I do this?

2 Answers

Answers 1

Try with:

RewriteEngine on RewriteRule html search.php [NC,L] 

If it does not work, you have another problem in .htaccess (Please indicate it in full in your question) or config.
Start by clearing your cache before testing. Or try with another browser.

Answers 2

You need to Proxy RewriteRule and mod_proxy

RewriteRule "/(.*)\.html$" "/search.php" [P]

Make sure to enable and configure mod_proxy properly. mod_proxy documentation can be found here.

Read More

Wednesday, August 9, 2017

Blocking IP range in htaccess file

Leave a Comment

I'm managing a site and the site is built in Wordpress. It gets ENORMOUS amount of traffic from bots and we want to block all of them except for important bots like Google Yahoo Bing Baidu. We use cloudflare and I want to block them from two layers, Cloudflare firewall and htaccess file. In htaccess file, I know how to block a single IP address and last trailing IPs of a IP range like 123.123.123.0/16

However, I need to block following IPs 69.30.192.0 - 69.30.255.255 93.55.115.64 - 93.55.115.71

How do you set rules of this in htaccess file? Cloudflare seems to follow same rule.

4 Answers

Answers 1

You've almost got it. The /16 notation is actually called CIDR Notation.

The number indicates how many bits to match from left to right. The Wiki page explains it in depth.

Or... you can just take my word for it and use a tool like this one I found: http://www.ipaddressguide.com/cidr#range

You can then use the deny from in your .htaccess just as you would for a single ip with the given values:

Order Allow,Deny Deny from 69.30.192.0/18 Deny from 93.55.115.64/29 Allow from all 

Answers 2

Not sure how reliable the source is, but this is from clockwatchers

http://www.clockwatchers.com/htaccess_block.html

To Block a single ip address

order allow,deny deny from 127.0.0.1 allow from all 

This will refuse all GET and POST requests made by IP address 127.0.0.1, an error message is shown instead

To block multiple ip addresses, list them one per line

order allow,deny deny from 127.0.0.1 deny from 127.0.0.2 deny from 127.0.0.3 allow from all 

To block an entire ip range

deny from 127.0.0 

This will refuse access for any user with an address in the 127.0.0.0 to 127.0.0.255 range.

Edit: Just found a similar question here

How to Block an IP address range using the .htaccess file

Looks like out answers are similar too.

Answers 3

The answer from @Nick is good, so on the side of configuring the .htaccess you should go his way.

My answer will be about another issue detected in your question: you are willing to block the IP range 69.30.192.0 - 69.30.255.255, but a quick search on the ARIN database (WHOIS for IP addresses) shows that this range is not belonging to a single person.

In fact, by doing this, you might potentially deny your website to non-bots.

Eg:

69.30.192.0 - 69.30.192.31 belongs to LEAKY****.COM

...

69.30.193.0 - 69.30.193.15 belongs to TA*****, Abdelkader

etc.

Answers 4

I have enjoyed recent success with the legacy GeoIP plugin for apache, nginx, and haproxy. Typically you can segment traffic by incoming geo.

http://dev.maxmind.com/geoip/legacy/mod_geoip2/

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

Monday, July 3, 2017

Font not loading - CORS says header contains no Access Control but there is

Leave a Comment

The problem: I am using html generated from one site that is being pushed to another site (different domains). All is working well except the font (used mainly for icons) is not showing up. I am receiving a CORS error as described further below.

I have added the following code to my .htaccess file on the site where the fonts are stored that allows fonts to be access across any domain:

<FilesMatch ".(eot|ttf|otf|woff)">     Header set Access-Control-Allow-Origin "*" </FilesMatch> 

I checked the header using cUrl:

curl -I https://mywebsite.com/fonts/flatpack.woff?tzy7cr HTTP/1.1 200 OK Server: nginx Date: Fri, 23 Jun 2017 18:33:58 GMT Content-Type: text/plain Content-Length: 142020 Connection: keep-alive X-Accel-Version: 0.01 Last-Modified: Fri, 23 Jun 2017 17:49:02 GMT ETag: "1a474c-22ac4-552a4378235b7" Accept-Ranges: bytes X-Powered-By: PleskLin Access-Control-Allow-Origin: * 

The Access Origin response tells me that the font should be readable but I'm still getting this error from the requesting website:

Access to Font at https://mywebsite/fonts/flatpack.woff?tzy7cr' from origin 'http://anotherwebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://anotherwebsite.com' is therefore not allowed access.

Thoughts or suggestions???

Edit: Here is a live link to a test page that fails to load the icon fonts.

2 Answers

Answers 1

Almost got it right:

Header add Access-Control-Allow-Origin "*" Header add Access-Control-Allow-Methods: "GET" 

You need to add the header not set. I'd also add the method to be sure.

Answers 2

Premium font purchased by some other website can be abused another site. That is the reason of complication at browser level coding. Image will not suffer such issue. Font related CORS is complicated by types of fonts, browsers and bugs. Unless you are using paid origin pull CDN or known font provider (free or paid), it is practical to serve font from own server for the sake of making sure that font loads on all browsers, all devices. It is worthy to read :

  1. official W3 doc about CORS,
  2. Mozilla doc,
  3. MaxCDN's guide,
  4. W3's CSS font doc,
  5. this old bug report
  6. this pull request

There are three options from the above resources for giving you a correct answer. You need to test from webpagetest dot org from different user agents & devices and try to watch the video of screenshot.

One :

SetEnvIf Origin "https?://(.*\.(mozilla|allizom)\.(com|org|net))" CORS=$0 Header set Access-Control-Allow-Origin %{CORS}e env=CORS  <FilesMatch "\.(ttf|woff|eot)$">     Header append vary "Origin"     ExpiresActive On     ExpiresDefault "access plus 1 year" </FilesMatch> 

Two (Single domain, HTTPS) :

<FilesMatch "\.(ttf|otf|eot|woff)$">         SetEnvIf Origin "^http(s)?://(.+\.)?anotherwebsite\.com$" AccessControlAllowOrigin=$0         Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin </FilesMatch> 

Three (Multiple domains) :

<FilesMatch "\.(ttf|otf|eot|woff)$">     <IfModule mod_headers.c>         SetEnvIf Origin "http(s)?://(www\.)?(anotherwebsite.com|cdn.anotherwebsite.com|blahblah.anotherwebsite.com)$" AccessControlAllowOrigin=$0         Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin     </IfModule> </FilesMatch> 

Also make sure that proper MIME types are present :

AddType application/vnd.ms-fontobject    .eot AddType application/x-font-opentype      .otf AddType image/svg+xml                    .svg AddType application/x-font-ttf           .ttf AddType application/font-woff            .woff AddType application/font-woff2           .woff2 

Make sure to run Apache configtest before restarting. You may need to activate some module.

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