Now Playing Tracks

Redirect non www URL to www URL using nginx

Its always recommended to host your website only in one URL either with www or without www. Suppose you prefer to go with www.example.com. In that case you have to redirect example.com visits to www.example.com. You can easily achieve it using your proxy server like apache or nginx. In this post we will tell you how to do it using nginx.

As described in our previous post  please first setup reverse proxy by adding server section in nginx configuration file. To redirect traffic add one more server section in configuration file i.e default.conf which can be found at /etc/nginx/conf.d//etc/nginx/conf.d . Below is sample code for  that. In this server section we are telling nginx that any request which come from example.com should be redirected to www.example.com (301 status code mean  permanent redirection)

// Redirection

server {

listen 80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}

Configuring Tomcat 7 with Nginx as proxy server in Centos

Why to use Nginx with Tomcat?

Usually you have a tomcat or other application server on port different from 80 . Its not desirable to access your application with port on URL something like http://www.example.com:8080 and so someway we have to host our application in port 80. One way or may be best way to achieve this is to use proxy web server like apache http server or Nginx server(By default they run in port 80).  Also proxy server has other advantages like security, load balancing, extended functionality (such as URL re-writing), and content caching.

So we had choice to make between apache and Nginx. We chose Nginx for several reason and one of them is nginx is faster at serving static files and consumes much less memory for concurrent requests because Nginx is event-based it doesn’t need to spawn new processes or threads for each request, so its memory usage is very low.

Configuration

I am assuming here that you already have your application deployed in tomcat at port 8080.  So you can access it from http://www.example.com:8080

  1. Get Nginx - Get the Nginx rpm url from its website and run wget command.                                                                                 wget http://nginx.org/packages/centos/6/x86_64/RPMS/nginx-1.4.4-1.el6.ngx.x86_64.rpm
  2. Install - Install nginx using rpm command.                                         rpm -ivh nginx-1.4.4-1.el6.ngx.x86_64.rpm
  3. Configure reverse proxy - For that you have to add new server section in server configuration file which is at /etc/nginx/conf.d//etc/nginx/conf.d  .    Add below code  in config (replace  www.example.com with your domain)

    server {
    server_name www.example.com;
    listen 80;

    location / {
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://localhost:8080;
    }
    }

  4. Restart Nginx - restart your server                                                    service nginx restart

That’s it now you can access your application at www.example.com.

AngularJS -Code Snippet

Let’s take one html like login form and see, how we can model it into Angular world.

I will explain the underlying concept, as we go along.The html page will be modified with angular mark-up so as to be picked by Angularjs.

<!DOCTYPE html>

<html ng-app=”reviewMatters”> 

<head

<script src=”http://code.angularjs.org/1.2.6/angular.min.js”></script>

<script src=”controllers.js”></script>

</head>

<body>

<div ng-controller=”LoginController as user”>

        <h3><span>Sign In</span></h3>

        <form  ng-submit=”submitLoginForm(true)”>

            <fieldset>

                <input ng-model=”user.email" type="email" required/>

                <input ng-model=”user.password" type="password"  required/>

                <button  type=”submit”>Sign in </button>

            </fieldset>

        </form>

     </div>

</body>

</html>

Lets see what we have done.The above file looks like a normal html file with some angular markup to make it angular aware.In angular world,it is called “Template".These markups starts with prefixes "ng-"  and are Angular built-in ‘directive’.

These all directives need to be decoded before browser can render it.The decoding is done via Angular "Compiler".Once it is decoded and ready to be rendered by browser,it is called"View".We have included two .js files, one -Angular library and other one is file that contains controller code for the above template.The controllers.js file contain the logic for controller as below:

angular.module(‘reviewMatters’, [])

    .controller(‘LoginController’, function($scope,$http) {

        var url = ‘user/login’;

        var data = angular.toJson($scope.user);

        $scope.submitLoginForm =function(){

            $http.post(url, data)

                .success(function (serverResponse) {

                    if (serverResponse.code == “200”) { //only on success

                       console.log (“User Logged In”);                      

                    } else {

                        console.log (“User Not Logged In”);                          

                    }

                })

                .error(function (data) {

                    console.log (“Some error occurred”);       

                });

       };           

    });

Let`s understand each of these “ng-” directives.

<html ng-app=”reviewMatters”> : The ng-app directive tells angular which parts of the page it should manage.We have placed it at root <html> element, we are telling angular that we want to manage whole page.It has also been given the name as “reviewmatters” for reference.This directive automatically initializes the application.

Next we define the controller scope as below.

<form ng-controller=”LoginController as user”>: Anything that comes under controller scope can be marked as ng-controller.Here the <form></form> becomes visible to controller.The data inside it is further put into model using ng-model directive.It is kept as “user” object with two property email and password.

The controller code is kept in the file controllers.js.

The model is treated as user object and that is why we have marked controller as user.The model finally is put into $scope (model in angular world) and this $scope is made available in the controller JS code using dependency injection as function parameter.Note that, we have also passed other variable called $http(we will discuss later).$http is used to send request to server.

We have used ng-submit, which is called when user submits the form.It in turns call the method in our controller(LoginController),where we take the “user" onject,change it to json format using angular.toJson() and send it to server for login.If login is successful, we print it to console otherwise error message is printed.

With this basic code snippet, I hope that you have fair ideas of how things work in Angular.We will add full Angularjs tutorial here slowly, keep on reading ……

Why we selected AngularJS for our UI

When we started development for ReviewMatters, we were looking for robust framework for our UI code handling. We were proficient in Java but UI/JavaScript was something which we had hated till date.As it was our start up, we were the lone warrior and we decided to take this challenge and worked towards finding the best framework for our UI development.

After doing research for about a week, we decided to go ahead Angularjs. The reasons why we chose this, were as below:

1). AngularJS development follows MVC paradigm like SpringMVC or Struts, thus making it lot easier for someone coming from Java background. MVC divides the structure into 3 entities called Model, View and Controller.

Model: It is something that captures the data. ($scope in Angularworld)

View: It is shown to the end user. Here it is a simple HTML page.

Controller: It does all kind of operations on data using helper classes (called Service, Factory or Provider in Angularjs world) which updates Model.

2).It also captures one of the very important design principles called “Dependency Injection”. Dependency Injection means giving an Object its instance variables on which it depends, So that the object does not have to create it itself.

3).It gives an awesome feature to bind View and Model together and any change in View will reflect immediately in Model or vice versa. The peoperty through which it is done is $scope.

4).As it uses Dependency Injection to manage its entities like Controllers and Helper Classes, writing unit test cases in AngularJS is a breeze. All these classes are well separated and thus testing any component is very easy.

5).DOM manipulation is part of every UI. Traditionally, we put in DOM manipulation code along with the code that present data in view. With AngularJS, DOM manipulation can be fully abstracted in the form of “Directives”, so that UI designers can focus on the view without any distraction.

6).Controllers interact with service classes further to update Models (In angular world, it is called $scope).These service classes abstract business functions, exception handling and server interaction.

The idea here is to keep Controller lean and dedicated to model/view and all heavy lifting work is delegated to service classes (Service, Factory or Providers).

Angularjs separates responsibilities in well defined elements and classes .It creates so many elements that communication between them brings in extra complexity.It becomes a pain initially to learn so many thing but believe it, once you pass initial hurdle,you realise the true worth of it.

Next, We will start with a code snippet, which will help in understanding above concept.

To Tumblr, Love Pixel Union