Apache rewrite : how avoid to display url parameter when the url final slash is omitted? - url-rewriting

In my .htacess of my domain, I must point subdomain to the 1rst GET parameter of the domain. The subdomain represents the language (for example en., fr, etc...).
In order to achieve this aim, here the rewrite code in the .htaccess :
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com$ [NC]
RewriteRule ^(.*)$ $1?lang=%1 [NC,L]
I create a directory named test. This directory contains just index.html file.
So when you type in the url bar of a browser en.example.com/test/,
the rewrite code works.
But if you type en.example.com/test without the final slash, it redirects to en.example.com/test/?lang=en => it's a problem.
So have you an idea to correct that ?
Thank you in advance, cordially.

When specifying xx.example.com/test/, an internal redirect
occurs to xx.example.com/test/?lang=xx. The client never sees the ?lang=xx.
However, when specifying xx.example.com/test, where test is a directory,
mod_dir steps in and rewrites the URL to xx.example.com/test/, but in
such a way that the rewrite rule for the ?lang=xx redirect becomes public,
having the client see xx.example.com/test/?lang=xx as the URL - which is unwanted.
In order to keep the '?lang=' redirect local (hidden from the client)
place this in the .htaccess, BEFORE the original rewrite rules:
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ $1/ [R,L]
The condition checks whether the requested filename is a directory,
and the rule forces a client-side redirect [R], so that a client requesting xx.example.com/test will be redirected to xx.example.com/test/.
The key however is the [L], which makes this rule the Last, preventing the following rules from executing. Without this L flag, the entire redirect from xx.example.com/test to xx.example.com/test/?lang=xx becomes public.
After the client is forcefully redirected to the proper URL with a terminating /, the rewrite rules doing the internal redirect adding the lang GET parameter are executed as normal.
Here's the entire .htaccess:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ $1/ [R,L]
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com$ [NC]
RewriteRule ^(.*)$ $1?lang=%1 [NC,L]
There is however another way to achieve this without using Apache config and internal redirect, and that is to examine $_SERVER['SERVER_NAME']:
<?php
list( $lang ) = explode('.', $_REQUEST['SERVER_NAME'] );

Related

How do you create domain redirect in Laravel htaccess but not on page alias

I have a domain alias that I want to stay as it is, but I want to redirect the main domain url.
http(and s)://www.alias.maindomain.com -> no redirect
http(and s)://www.maindomain.com -> redirect to given url
I have a Laravel project and this is my htacess.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule "^http://www.maindomain.com" "http://www.redirectedpage.com"
I tried redirecting the routes in laravel but that wasnt working so think the htacess file is the way to go?
To redirect only www.maindomain.com/ to https://www.redirectpage.com/ you would need to do something like the following at the top of your .htaccess file, before the Laravel directives.
RewriteCond %{HTTP_HOST} =www.maindomain.com
RewriteRule ^$ https://www.redirectpage.com/ [R=302,L]
The RewriteRule pattern (the first argument to the RewriteRule directive) matches the requested URL-path only (less the directory-prefix when used in a .htaccess context, so there is no slash prefix). In this case, the RewriteRule pattern ^$ matches an empty URL-path, corresponding to the requested URL / (ie. the document root).
To match the requested hostname you need to use a condition (RewriteCond directive) and check against the HTTP_HOST server variable - which contains the value of the Host HTTP request header.
The CondPattern =www.maindomain.com (with a = prefix) is an exact match string comparison, not a regex.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule "^http://www.maindomain.com" "http://www.redirectedpage.com"
I'm not sure why you are checking that the request does not map to a physical file. If you want to redirect a specific URL, then it presumably does not matter whether that URL maps to a file (or directory).
As mentioned above, the RewriteRule pattern matches against the requested URL-path. So, the regex ^http://www.maindomain.com will never match.

How to redirect httaccess

I tried to redirect but not working even I put the correct code from take it from web.
Redirect /index.php?page=8 /?page=8
Redirect /index.php?page=8 /?page=8
The mod_alias Redirect directive does not match against the query string, so the above directive will never match, so does nothing.
To remove the index.php (directory index) from the visible URL, you would need to use mod_rewrite at the top of your .htaccess file. For example:
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index\.php$ / [R=301,L]
The above will redirect a URL of the form /index.php?page=8 to /?page=8. Any query string present on the initial request is simply passed through to the target/substitution unaltered.
The condition that checks against the REDIRECT_STATUS env var ensures we don't get a redirect loop caused by mod_dir (or the Laravel front-controller) rewriting the request to index.php.
Clear your browser cache and test first with a 302 (temporary) redirect.
However, if you did only want to redirect the specific URL /index.php?page=8 (as stated in the question) to /?page=8 then you should write the rule like the following instead:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,7}\s/index\.php?page=8\sHTTP
RewriteRule ^index\.php$ / [R=301,L]
Your htaccess code should be.
RewriteEngine On
RewriteRule ^index.php?page=$1 /?page=$1 [R=301,NC,L]

Redirect URL with htaccess

A third party plugin returns to an incorrect URL from a call to save a change.
The URL is /admin/?page=configure/admin/. The correct return should be to /lists/admin/?page=configure. My attempt to write a redirect failed with a 500 server error.
RewriteEngine On
RewriteRule ^(.*)/admin/(.*)$ $1/lists/admin/$2 [NC,L]
How can I correct this code?
This should work.
RewriteEngine On
RewriteCond %{REQUEST_URI} !^lists
RewriteRule ^(.*/)?admin/(.*)$ $1lists/admin/$2 [QSA,L]
If you want to match a different folder to redirect to admin you will have to declare it literally as a pattern like ^(.*)?/admin would also match lists/admin and cause a loop.

Rewrite link rule, conflicting files and folders

Been trying to resolve this problem with a rewrite rule that assigns a subdomain to a root directory of the same name, for example.
ddd.example.com will link to "/_projects/ddd" directory, that works fine and I have no trouble with it, the issue is that any files or directories I have in the root directory "/" can be accessed from the subdomain ddd.example.com.
Here is an example directory structure
example.com = "/"
"index.php"
ddd.example.com = "/_projects/ddd"
no files
So if for instance I access ddd.example.com/index.php, it will resolve to using the file located example.com/index.php which is located a directory below.
Here is the rewrite rule for .htaccess
# Skip rewrite if subdomain is www
RewriteCond %{HTTP_HOST} !^www\. [NC]
# Extract (required) subdomain to %1
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com(:80)?$
# Redirect to domain if requested URL does not resolve to existing subdirectory path
RewriteCond %{DOCUMENT_ROOT}/_projects/%1 !-d
RewriteRule (.*) http://example.com/ [NC,R=301]
# Skip rewrite if subdomain is www
RewriteCond %{HTTP_HOST} !^www\. [NC]
# Extract (required) subdomain to %1
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com(:80)?$
# Skip rewrite if requested URL does not resolve to existing subdirectory path or file
RewriteCond %{DOCUMENT_ROOT}/_projects/%1/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/_projects/%1/$1 -d
RewriteRule (.*) /_projects/%1/$1 [NC,L]
What if your RewriteConds fail? Then the URL falls through and is not rewritten. And so it accesses the document root. I would just create separate VirtualHost entries for every single supported subdomain. (How many are there?)
Suppose the client asks for http://sub.example.com/index.php.
Suppose that there exists an /_projects/sub/index.php.
Your RewriteCond-s will see that /_projects/sub/index.php exists as a file, and then skip the rewrite. But if the rewrite is skipped, then there is no redirect to /_projects/sub/. So what document is fetched in that case? You guessed it, /index.php.
You should unconditionally redirect these subdomains to their proper places (subject only to checks against looping).
Why did you split the rewrite into two, one doing an internal redirect? The internal redirect isn't rewriting the whole URL to example.com, and so it stays in the subdomain. It looks like you can get into a loop there.
My attempt at rewriting was to do this essentially.
Pseudo Code:
if (subdomain-directory != exists)
redirect them to the home page
else
rewrite the request for the subdomain
I could only accomplish that using two rules, I haven't found any other way to accomplish this, so this was my attempt.
The condition in question actually works fine, if I have an index.php in the /_projects/sub directory then it will use that file and the same for any other file I put in there.
I have absolutely no idea how I can accomplish this with mod_rewrite, I have played around with it for the best part of a few weeks to no avail, searched endlessly for possible solutions and have not made any progress.
Resolved the problem, seems that there was a looping problem that was breaking the rewrite.
##### Subdomain to subfolder
# Fix missing trailing slashes.
#RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$ [NC]
#RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.example\.com$ [NC]
#RewriteCond %{DOCUMENT_ROOT}/%2%{REQUEST_URI}/ -d
#RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]
# Rewrite sub domains.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.example\.com$ [NC]
RewriteRule ^(.*)$ /projects/%2/$1 [QSA,L]

Rewrite Rule(s) for domain aliases

Situation: I have a single (main) domain, which has several aliased domains, each of which are pointing at the same Plesk-based server (for instance, I have example.com as main, with something.net, anotherone.co.uk, and several others all as aliases of the main domain account). This means that whenever I enter the domain name into my address bar of any of the aliases, it goes directly to the account of the main domain (example.com).
Problem: Based on the domain name of the alias(es), I have an index.php that redirects each domain differently (for instance, requests to domain A redirects to a corporate site, domain b goes to a thanks site etc.) Which works great, but if a directory is added after the domain URL (i.e. somealias.com/something) then it gives a 404 not found error.
What I would really appreciate, if someone can help me out, is a (single if possible) rewrite ruleset that would essentially strip off ALL trailing directories and/or GET requests, and only leave the typed-in base URL, so then the php script sitting in the main domain document root can take over and deal with the request appropriately.
Strangely enough, I've not been able to find a (simple) solution for this anywhere. Is it a case of having to define a rule for each of the aliased domains individually?
Try the following,
#Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.olddomain.com$[OR]
RewriteCond %{HTTP_HOST} ^olddomain.com$
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !=/
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule .* http://%{HTTP_HOST}/? [L]
This will take ALL requests except root folder / (e.g. http://example.com/) or index file (e.g. http://example.com/index.php) and redirect them to the root folder (e.g. http://example.com/some-url will be redirected to http://example.com/).
You may need to replace index.php by the file that is get executed when you hit the root folder (Apache will silently rewrite http://example.com/ to http://example.com/index.php (depending on your actual settings) as it needs to have a file to execute otherwise it may show an error).
Alternatively (possibly even better -- depends on your actual setup and requirements) you may use these rules -- this will redirect only non-existing URLs. So if you have an image meow.png on your site, these rules will allow you to access it (http://example.com/meow.png):
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* http://%{HTTP_HOST}/? [L]
UPDATE:
If you going to place this into config file (httpd-vhost.conf or httpd.conf) then use these rules:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule .* http://%{HTTP_HOST}/? [L]
It seems to me that all the sites are hosted on the same server (probably using the same code base).
If your index.php is a front controller you can redirect everything to your index.php and decide in the first lines of index.php what front controller to load (like backend.php).
If you don't mind having to maintain a list of the aliases you can define a hash of [alias] => path-to-front-controller.
In the front controller of you main domain you check the alias name (using $_SERVER['SERVER_NAME'] for example) against the hash and load the appropriate file.
You will have to add and entry to the hash each time you add anew alias. If they are not generated dynamically maintaining this hash is not a lot of hassle.

Resources