.htaccess - Rewrite wildcard for a specific folder - .htaccess

I want to redirect anything that comes in on:
http://example.com/api/ /* e.g. http://example.com/api/anything */
to:
http://localhost:3002/api/ /* e.g. http://localhost:3002/api/anything */
Here's what I'm trying but fails:
RewriteEngine On
RewriteRule ^api/ http://localhost:3002/api/ [R=301,L]
I know I could do routes individually e.g.
Redirect 301 /api/thisaddress http://localhost:3002/api/thisaddress
But would rather have a wildcard... is there a way to do this?
UPDATE
As the web page is a single page app, I currently already have in my .htaccess file:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /index.html [L]

You can use:
RewriteEngine On
RewriteRule ^api/ http://localhost:3002%{REQUEST_URI} [NE,NC,R=301,L]
%{REQUEST_URI} represents original URI starting with /api/...
Alternatively, you can also use:
RewriteRule ^api/.*$ http://localhost:3002/$0 [NE,NC,R=301,L]

Related

Redirect URLs with specific pattern to same URL in subsite

Update : By the help of answers, I am able to have this update. I want following expression in my .htaccess to be working . (Complete script of .htaccess is shared in question as well)
RewriteCond %{REQUEST_URI} ((mypage2(/\d{4}-\d{2}-\d{2})?/\d{1,2}) |about-us)
RewriteRule ^(.+)$ /subsite/#/$1 [R=301,NC]
Detail Of Question:
I have added angularjs subsite to an exsiting expressionengine php site.
subsite contains only three pages, which were very slow in existing website
I want htacces to redirect those three urls to new subsite urls e.g mydomain/page2/parameter1/parameter2 to mydomain/subsite/#/page2/parameter1/parameter2 and mydomain/page2/parameter1 to mydomain/subsite/#/page2/parameter1
(This is not compulsory) In subsite I want to clean up/manipulate Urls using history push state to show user
mydomain/page2/parameter1/parameter2 instaed of mydomain/subsite/#/page2/parameter1/parameter2
My .htaccess is like
RewriteEngine On
RewriteBase /
# Removes index.php from ExpressionEngine URLs
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteCond %{REQUEST_URI} !/system/.* [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
# Directs all EE web requests through the site index file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/#/$1 [L,QSA]
Following is most wanted thing to me
RewriteCond %{REQUEST_URI} ((mypage2(/\d{4}-\d{2}-\d{2})?/\d{1,2}) |about-us)
RewriteRule ^(.+)$ /subsite/#/$1 [R=301,NC] ==> when url is like mypage2(/date optional)/pagenumber then redirect it to subsite/#/mypage2(/date optional)/pagenumber
Also this is optional, I can live if following is not achieved
In my routing.js I want to manipulate urls like
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams,
fromState, fromParams, options, Data) {
var cleanUrl = window.location.toString().replace(subsite+'/#/', '');
window.history.pushState(null, null, cleanUrl);
//alert("Yes this works, it shows me the required url in browser at this moment");
//Here I am trying to clean the url
//But after that it reloads, some unwanted redirection happens after it
});
Okay, Try with below rule,
RewriteEngine On
RewriteCond %{REQUEST_URI} ^!(aSpecialString2|aSpecialString1|/)
RewriteRule ^(.+)$ /#/$1 [R=301,NC]
Here you will not get the #/uri in url but you will get %23 html entity which will respond as same as # in url and your app will work.
And I am assuming you will get the way to work it out with angular.
You can use mod_rewrite and php in the server side to this task
Create an index.php
<?php
if ( !empty($_GET['id']) ) {
$protocol = 'http://';
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
$protocol = 'https://';
}
header('Location:' . $protocol . $_SERVER["HTTP_HOST"]. '/#/' . $_GET[id]);
exit();
}
?>
You html here
Add the following in your .htaccess
RewriteEngine On
RewriteBase /
RewriteRule "index.php" - [L]
RewriteRule "^(.*)$" "index.php?id=$1"
To bypass some urls aString1,aString2 you can use:
RewriteEngine On
RewriteBase /
RewriteRule "index.php" - [L]
RewriteCond %{REQUEST_URI} !^(aString1)
RewriteCond %{REQUEST_URI} !^(aString2)
RewriteRule "^(.*)$" "index.php?id=$1"
To bypass assets you can use:
RewriteEngine On
RewriteBase /
RewriteRule "index.php" - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule "^(.*)$" "index.php?id=$1"
Now, http://example.com/s1/s2 will redirect to http://example.com/#/s1/s2
You can use mod_rewrite and javascript snippet in the client side to this task
Add the following to .htaccess
RewriteEngine On
RewriteBase /
RewriteRule "^([^?#].*)$" "/?$1" [R=301,NC]
Add following to main html
<script>
window.onload = function() {
location.hash = '/' + location.search.substr(1)
}
</script>
Now, http://example.com/s1/s2 will redirect to http://example.com/?s1/s2#/s1/s2
As your question states clearly you only need your html client routes to always have # right after domain name, here is a simple way to achieve it
As you are asking this for angular, so its very easy in that case. Just paste following code in element of index.html
<script>
var currentSitePageUrl = window.location.toString();
if(currentSitePageUrl.indexOf('#/') == -1)
{
window.location = currentSitePageUrl.replace(yourDomainUrl+'#/')
}
}
</script>
Above will include # to each url request and rest of the url will stay as it is, but only when it is requesting some front-end page
If you have access to .htaccess on your server, you can modify it to work with the URLs in your code without inserting the #.
There are really 2 parts to this, one enabling HTML5Mode in your Angularjs app and 2 editing the .htaccess file on your server to deal with this successfully.
I don't PHP at all, but was able to get this working for several sites following this article: https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/#thecode
try this:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} /(mypage2(/.*)|about-us) # you used mypage2, so it will be redirected to subsite/#/mypage2
RewriteRule ^(.+)$ /subsite/#/$1 [R=301,NC]
# Removes index.php from ExpressionEngine URLs
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteCond %{REQUEST_URI} !/system/.* [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
# Directs all EE web requests through the site index file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/#/$1 [L,QSA]
notice the comment of the first rule.
and you can try your rules in sites like this: http://htaccess.mwl.be/

.htaccess serving other files if specific files are not found

If I have /index.html and the user goes to domain.tld or domain.tld/index.html I want them to get that page. (Default behavior)
If I don't have /index.html but I do have /content.txt I'd like to serve the page /makeindex.php but not change the url.
If I don't have /index.html or /content.txt I'd like to serve /nocontent.php but not change the url.
So far I have:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /makeindex.php [L]
But I don't know how to limit this to domain.tld or domain.tld/index.html and I also don't know how I would create that two step process first checking for content.txt if I serve /makeindex.php or falling back to /nocontent.php if both those files don't exist.
You can use the following rule, put this at the top of your htaccess :
RewriteEngine on
#if /index.html exists serve it as a directory index and main page
RewriteCond %{DOCUMENT_ROOT}/index.html -f
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ /index.html [L]
#if content.txt exists , use makeindex.php as directory index
RewriteCond %{DOCUMENT_ROOT}/content.txt -f
RewriteRule ^$ /makeindex.php [L]
#else set /nocontent.php as directory index
RewriteRule ^$ /nocontent.php [L]

.htaccess rewrite if nothing specified

I'm trying to modify my .htaccess file to link to three different places, based on the input after the endpoint:
"/api" - Link to the API
"/ABCD123" - If it's a 7 character
alphanumeric string, link to a specific page
"/" - If nothing specified, or for any other inputs link to the homepage.
Here is my .htaccess file:
Options -Indexes
RewriteEngine On
RewriteRule ^api/(.*) ./api/index.php [R,L]
RewriteRule ^([a-zA-Z0-9]{7})$ index.php?l=$1 [L]
RewriteRule ^(.+)$ everythingelse.php [L]
Even though I have the [L] flag specified I always seem to get redirected to the everythingelse.php route, even if I have the 7 character string.
How can I rewrite to match this correctly?
Your rules are looping and executing more than once. L flag only breaks current loop but mod_rewrite can loop again and execute all the matching rules.
Options -Indexes
RewriteEngine On
# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
RewriteRule ^api/(.*)$ /api/index.php [R,L]
RewriteRule ^([a-zA-Z0-9]{7})$ index.php?l=$1 [L,QSA]
RewriteRule . everythingelse.php [L]

htacces redirect for SEO friendly URLs

I have my htaccess file setup, so that the pages remove extensions. Now, I am trying to make the pages that transfer variables, into SEO friendly urls ... so, for example...
http://www.example.com/art-gallery?page=2 ... which is actually "art-gallery.php?page=2", would turn into... http://www.example.com/art-gallery/page/2
Or... http://www.example.com/art-piece?id=3 ...would go to... http://www.example.com/art-piece/id/3
... and so on ...
I have alot in my htaccess file, and am not sure how to do the above (there are plenty of tutorials on going from www.example.com/index.php?page=2 to www.example.com/page/2/ but none that do exactly what I need). Ideally, I'd like to be able to do this for all similar pages...
# enable the rewrite engine
RewriteEngine On
# Set your root directory
RewriteBase /
# Force www:
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
# Remove the .php extension
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]
# Remove index and reference the directory
RewriteRule (.*)/index$ $1/ [R=301]
# Remove trailing slash if not a directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]
# Forward request to html file, **but don't redirect (bot friendly)**
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]
# Disable Directory Browsing
Options -Indexes
# Disable Hotlinking of Images
# with forbidden or custom image option
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ – [NC,F,L]
# Protect htaccess File
<files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</files>
You can transfer parameters with the variable QUERY_STRING.
Consider the following rule:
RewriteRule ^index.html index.php?%{QUERY_STRING}&m=main&a=index
This rule would transform
index.html?something=value
into
index.php?something=value&m=main&a=index
You should use the RewriteEngine.
You could also use a 301 redirect either alone or in conjunction with the RewriteEngine to redirect SEs.
Generally, though redirecting SEs to a different page than what users will see is not a good practice, and may result in your pagerank decreasing. Instead, try migrating all your pages to the second URL format, and consider using 301 redirects to help the transition.
Generally: Use 301 redirects for SE-friendly page changes. See this SO for additional reference.
You can insert this rule just before Forward request to html file rule:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/])/([^/])/([^/])/?$ $1.php?$2=$3 [L,QSA]
This is quite old but why not do the following:
RewriteEngine On
RewriteRule ^([^?]*) index.php?route=$1 [L,QSA]
Then in your index.php you can handle it like such;
if (isset($_GET['route'])) {
$route = explode('/', $_GET['route']);
if (iconv_strlen((end($parts)), 'UTF-8') == 0) {
array_pop($parts);
}
}
From here your main level would be handled with $route[0], second level $route[1]
For example;
http://example.com/art-gallery/2
$route[0] would equal 'art-gallery'
$route[1] would equal '2'

Subdirectory URL rewriting PHP

Setup
I have my file structure set up as so:
/root
|
/api
|
/Slim PHP framework
index.php
|
index.php
The index.php inside the Slim directory contains the routes required to retrieve the JSON data from a Mongo database. E.g.
$app->get('/users(/:id)', function($id = null) use ($app, $collection) {
/* Do mongo search and echo json_encoded data back */
});
I have an .htaccess file contains: which removes the .php extension from files under the root.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php`
Question
I can access my JSON data using url: http://localhost:8888/root/api/index.php/users.
However, what I would like to do is access the data using the url: http://localhost:8888/root/api/users
If I understand correctly, what about this?
RewriteRule ^api/users/(.*)$ /root/api/index.php/users/$1 [L]
RewriteRule ^api/users$ /root/api/index.php/users [L]
That should allow this URL.
http://localhost:8888/api/users/1
and it will allow this too
http://localhost:8888/api/users
EDIT:
That should allow you to add a number after users. Also shortened the URL so you don't have to include root in the URL as well.
Assuming, your .htacces is located in website root "/"
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteCond %{REQUEST_URI} !/index.php [NC]
RewriteRule ^(.*?/api)/(.*)$ $1/index.php/$2 [NC,L]
This would redirect
http://localhost/root/api/users/1 => http://localhost/root/api/index.php/users/1
http://localhost/root/api/data/20 => http://localhost/root/api/index.php/data/20
One thing of note, the sequence of rules is also important, so if you need to rewrite/redirect http://example.com/users AND http://example.com/users/ to http://example.com/userinfo/ while at the same time rewriting http://example.com/users/uname to http://example.com/scripts/script.php?id=uname then this one should work: RewriteEngine on
RewriteEngine on
RewriteRule ^users/$ /userinfo/ [L]
RewriteRule ^users/(.*)$ /scripts/script.php?id=$1 [L]
RewriteRule ^users$ /userinfo/ [L]
There could be a better solution with one line less but this one works for me.

Resources